SDK

SDK React

@authon/reactComposants et hooks React pour Authon. Fonctionne avec Create React App, Vite et tout projet React 18+.

npm: @authon/reactReact 18+TypeScript

Installation

bash
npm install @authon/react

AuthonProvider

Enveloppez la racine de votre application avec AuthonProvider. Tous les hooks et composants doivent être rendus à l'intérieur de ce fournisseur.

src/main.tsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { AuthonProvider } from "@authon/react";
import App from "./App";

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <AuthonProvider publishableKey="pk_live_your_publishable_key">
      <App />
    </AuthonProvider>
  </StrictMode>
);

Props du fournisseur

PropTypeDescription
publishableKeystringYour pk_live_ or pk_test_ key from the dashboard
config.apiUrlstring?Override the Authon API base URL
config.theme'light' | 'dark' | 'auto'Color theme for the modal (default: auto)
config.localestring?Locale string for the modal UI (default: en)
config.appearancePartial<BrandingConfig>?Override branding config programmatically

Hooks

useAuthon()

Le hook principal pour interagir avec l'état d'authentification. Retourne la valeur complète du contexte, y compris les méthodes pour ouvrir le modal, obtenir le jeton et se déconnecter.

tsx
import { useAuthon } from "@authon/react";

function Header() {
  const {
    isSignedIn,
    isLoading,
    user,
    openSignIn,
    openSignUp,
    signOut,
    getToken,
  } = useAuthon();

  if (isLoading) return <Spinner />;

  return (
    <nav>
      {isSignedIn ? (
        <>
          <span>Hello, {user?.displayName}</span>
          <button onClick={() => signOut()}>Sign out</button>
        </>
      ) : (
        <button onClick={() => openSignIn()}>Sign in</button>
      )}
    </nav>
  );
}

useUser()

Un hook ciblé qui retourne uniquement les données utilisateur et l'état de chargement. Utilisez-le dans les composants qui n'ont besoin que d'afficher des informations utilisateur.

tsx
import { useUser } from "@authon/react";

function ProfileCard() {
  const { user, isLoading } = useUser();

  if (isLoading) return <Skeleton />;
  if (!user) return null;

  return (
    <div className="profile-card">
      {user.avatarUrl && (
        <img src={user.avatarUrl} alt={user.displayName ?? ""} />
      )}
      <h2>{user.displayName}</h2>
      <p>{user.email}</p>
      <span>Member since {new Date(user.createdAt).getFullYear()}</span>
    </div>
  );
}

Composants

SignedIn / SignedOut

Affiche ou masque les enfants en fonction de l'état d'authentification. C'est le moyen le plus simple de créer des interfaces adaptées à l'authentification sans conditions manuelles.

tsx
import { SignedIn, SignedOut } from "@authon/react";

function App() {
  return (
    <>
      <SignedIn>
        {/* Only rendered when user is signed in */}
        <Dashboard />
        <UserButton />
      </SignedIn>

      <SignedOut>
        {/* Only rendered when user is NOT signed in */}
        <LandingPage />
        <SignInButton />
      </SignedOut>
    </>
  );
}

SignIn / SignUp

Déclenche l'interface modal Authon. En mode popup , le modal s'ouvre au montage. En mode embedded , le formulaire est rendu en ligne.

tsx
import { SignIn, SignUp } from "@authon/react";

// Popup — opens the modal when mounted
function LoginPage() {
  return <SignIn mode="popup" />;
}

// Embedded — renders a form container in-place
function SignUpPage() {
  return (
    <div className="flex min-h-screen items-center justify-center">
      <SignUp mode="embedded" />
    </div>
  );
}

UserButton

Bouton avatar clé en main avec un menu déroulant de déconnexion. Affiche l'avatar de l'utilisateur si disponible, ou revient aux initiales avec un fond dégradé. Retourne null lorsqu'aucun utilisateur n'est connecté.

tsx
import { UserButton } from "@authon/react";

function AppHeader() {
  return (
    <header className="flex items-center justify-between p-4">
      <Logo />
      <UserButton />
    </header>
  );
}

Routes protégées

CombinezuseAuthon()avec React Router pour protéger les routes privées :

components/ProtectedRoute.tsx
import { Navigate } from "react-router-dom";
import { useAuthon } from "@authon/react";

interface ProtectedRouteProps {
  children: React.ReactNode;
  redirectTo?: string;
}

export function ProtectedRoute({
  children,
  redirectTo = "/sign-in",
}: ProtectedRouteProps) {
  const { isSignedIn, isLoading } = useAuthon();

  if (isLoading) return <FullPageSpinner />;
  if (!isSignedIn) return <Navigate to={redirectTo} replace />;

  return <>{children}</>;
}

// Usage in router
const router = createBrowserRouter([
  { path: "/", element: <Home /> },
  {
    path: "/dashboard",
    element: (
      <ProtectedRoute>
        <Dashboard />
      </ProtectedRoute>
    ),
  },
]);

Utilisation du jeton

UtilisezgetToken() pour joindre le JWT à vos appels d'API backend :

tsx
import { useAuthon } from "@authon/react";

function useApi() {
  const { getToken } = useAuthon();

  const apiFetch = async (path: string, init?: RequestInit) => {
    const token = getToken();
    return fetch(`/api${path}`, {
      ...init,
      headers: {
        ...init?.headers,
        Authorization: token ? `Bearer ${token}` : "",
        "Content-Type": "application/json",
      },
    });
  };

  return { apiFetch };
}

// In a component
function OrdersList() {
  const { apiFetch } = useApi();
  const [orders, setOrders] = useState([]);

  useEffect(() => {
    apiFetch("/orders").then((r) => r.json()).then(setOrders);
  }, []);

  return <ul>{orders.map((o) => <li key={o.id}>{o.name}</li>)}</ul>;
}
Authon — Plateforme d’authentification universelle