> ## Documentation Index
> Fetch the complete documentation index at: https://translations.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Ajouter la fonctionnalité Login à votre application Express

> Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les renseignements du profil utilisateur dans une application web Express.js à l’aide du SDK @auth0/auth0-express (Beta).

export const CreateInteractiveApp = ({placeholderText = "Auth0", appType = "regular_web", allowedCallbackUrls = ["localhost:3000"], allowedLogoutUrls = ["localhost:3000"], allowedOriginUrls = ["localhost:3000"]}) => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [storeReady, setStoreReady] = useState(false);
  const [displayForm, setDisplayForm] = useState(true);
  useEffect(() => {
    const init = () => setStoreReady(true);
    if (window.rootStore) {
      window.rootStore.clientStore.setSelectedClient(null);
      window.rootStore.clientStore.setSelectedClientSecret(undefined);
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
    };
  }, []);
  useEffect(() => {
    if (!storeReady) return;
    const disposer = autorun(() => {
      const rootStore = window.rootStore;
      setIsAuthenticated(rootStore.sessionStore.isAuthenticated);
    });
    return () => {
      disposer();
    };
  }, [storeReady]);
  if (!storeReady || typeof window === "undefined" || !displayForm) {
    return <></>;
  }
  const login = () => {
    const baseUrl = window.rootStore.config.apiBaseUrl;
    const returnTo = encodeURIComponent(window.location.href);
    window.location.href = `${baseUrl}/auth/user/login?returnTo=${returnTo}`;
  };
  const Card = ({className = "", children}) => {
    return <div className={`
          flex border rounded-2xl
          border-gray-950/10 dark:border-white/10
          py-3.5 px-4 gap-2
          text-sm text-gray-900 dark:text-gray-200
          ${className}
        `}>
        {children}
      </div>;
  };
  const Button = ({children, ...props}) => {
    return <button className="bg-[--button-primary] text-[--foreground-inverse] px-[1.125rem] py-1.5 rounded-lg font-medium" {...props}>
        {children}
      </button>;
  };
  const CreateApplicationForm = () => {
    const [name, setName] = useState("");
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState("");
    const handleSubmit = async () => {
      if (!name.trim()) {
        setError("Le nom de l'application est obligatoire");
        return;
      }
      setIsLoading(true);
      setError(null);
      try {
        await window.rootStore.clientStore.createClient({
          name: name.trim(),
          app_type: appType,
          callbacks: allowedCallbackUrls,
          allowed_logout_urls: allowedLogoutUrls,
          web_origins: allowedOriginUrls,
          client_metadata: {
            created_by: "quickstart-docs-app-creation-component"
          }
        });
        setDisplayForm(false);
      } catch (err) {
        console.error("Erreur lors de la création du client :", err);
        const errorMessage = err instanceof Error ? err.message : "Échec de la création de l'application";
        setError(errorMessage);
      } finally {
        setIsLoading(false);
      }
    };
    return <Card className="flex-col items-start p-4 gap-3.75">
        <span className="font-medium text-gray-900 dark:text-gray-200">Créer une Auth0 App</span>
        <div className="w-full flex gap-2">
          <input id="app-name" name={name} className="
              w-full max-w-[448px] h-11 py-2 px-4 
              border rounded-lg border-gray-950/10 dark:border-white/10 
              text-gray-900 dark:text-gray-200
              focus:outline-none dark:focus:outline-none
            " placeholder={`Mon application ${placeholderText}`} value={name} onChange={e => setName(e.target.value)} />
          <Button onClick={handleSubmit}>{isLoading ? "Création en cours..." : "Créer"}</Button>
        </div>
        {error && <p className="text-red-500">{error}</p>}
      </Card>;
  };
  const SignInForm = () => {
    return <Card className="items-center">
        <Button onClick={login}>Se connecter</Button> <span>pour créer l'application</span>
      </Card>;
  };
  return isAuthenticated ? <CreateApplicationForm /> : <SignInForm />;
};

export const AuthCodeGroup = ({children, dropdown}) => {
  const [processedChildren, setProcessedChildren] = useState(children);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      unsubscribe = window.autorun(() => {
        const processChildren = node => {
          if (typeof node === "string") {
            let processedNode = node;
            for (const [key, value] of window.rootStore.variableStore.values.entries()) {
              const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
              processedNode = processedNode.replaceAll(new RegExp(escapedKey, "g"), value);
            }
            return processedNode;
          } else if (Array.isArray(node)) {
            return node.map(processChildren);
          } else if (node && node.props && node.props.children) {
            return {
              ...node,
              props: {
                ...node.props,
                children: processChildren(node.props.children)
              }
            };
          }
          return node;
        };
        setProcessedChildren(processChildren(children));
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  return <CodeGroup dropdown={dropdown}>{processedChildren}</CodeGroup>;
};

export const AuthCodeBlock = ({filename, icon, language, highlight, children}) => {
  const [displayText, setDisplayText] = useState(children);
  const [copyText, setCopyText] = useState(children);
  const wrapperRef = React.useRef(null);
  useEffect(() => {
    let unsubscribe = null;
    function init() {
      if (!window.autorun || !window.rootStore) {
        return;
      }
      unsubscribe = window.autorun(() => {
        let processedChildrenForDisplay = children;
        let processedChildrenForCopy = children;
        for (const [key, value] of window.rootStore.variableStore.values.entries()) {
          const escapedKey = key.replaceAll(/[.*+?^${}()|[\]\\]/g, (String.raw)`\$&`);
          let displayValue = value;
          if (key === "{yourClientSecret}" && value !== "{yourClientSecret}") {
            displayValue = value.substring(0, 3) + "*****MASQUÉ*****";
          }
          processedChildrenForDisplay = processedChildrenForDisplay.replaceAll(new RegExp(escapedKey, "g"), displayValue);
          processedChildrenForCopy = processedChildrenForCopy.replaceAll(new RegExp(escapedKey, "g"), value);
        }
        setDisplayText(processedChildrenForDisplay);
        setCopyText(processedChildrenForCopy);
      });
    }
    if (window.rootStore) {
      init();
    } else {
      window.addEventListener("adu:storeReady", init);
    }
    return () => {
      window.removeEventListener("adu:storeReady", init);
      unsubscribe?.();
    };
  }, [children]);
  useEffect(() => {
    if (!wrapperRef.current) return;
    const originalWriteText = navigator.clipboard.writeText.bind(navigator.clipboard);
    let isOverriding = false;
    const handleClick = e => {
      const button = e.target.closest('[data-testid="copy-code-button"]');
      if (!button || !wrapperRef.current.contains(button)) return;
      isOverriding = true;
      navigator.clipboard.writeText = text => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
          return originalWriteText(copyText);
        }
        return originalWriteText(text);
      };
      setTimeout(() => {
        if (isOverriding) {
          isOverriding = false;
          navigator.clipboard.writeText = originalWriteText;
        }
      }, 100);
    };
    const wrapper = wrapperRef.current;
    wrapper.addEventListener('click', handleClick, true);
    return () => {
      wrapper.removeEventListener('click', handleClick, true);
      if (navigator.clipboard.writeText !== originalWriteText) {
        navigator.clipboard.writeText = originalWriteText;
      }
    };
  }, [copyText]);
  return <div ref={wrapperRef}>
      <CodeBlock filename={filename} icon={icon} language={language} lines highlight={highlight}>
        {displayText}
      </CodeBlock>
    </div>;
};

export const HowToSchema = () => <script type="application/ld+json">
    {'{"@context":"https://schema.org","@type":"HowTo"}'}
  </script>;

<HowToSchema />

export const envSnippet = `AUTH0_DOMAIN={yourDomain}
AUTH0_CLIENT_ID={yourClientId}
AUTH0_CLIENT_SECRET={yourClientSecret}
APP_BASE_URL=http://localhost:3000
AUTH0_SESSION_SECRET=use-a-long-random-string-at-least-32-characters`;

export const envSnippetDashboard = `AUTH0_DOMAIN=YOUR_AUTH0_DOMAIN
AUTH0_CLIENT_ID=YOUR_AUTH0_CLIENT_ID
AUTH0_CLIENT_SECRET=YOUR_AUTH0_CLIENT_SECRET
APP_BASE_URL=http://localhost:3000
AUTH0_SESSION_SECRET=use-a-long-random-string-at-least-32-characters`;

<Warning>
  Ce Quickstart est actuellement en **Beta**. Nous serions ravis de connaître vos commentaires!
</Warning>

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  **Prérequis :** Avant de commencer, assurez-vous d’avoir installé les éléments suivants :

  * [Node.js](https://nodejs.org/) 22 LTS ou version ultérieure
  * [npm](https://www.npmjs.com/) 10+ ou [yarn](https://yarnpkg.com/) 1.22+
</Callout>

<div id="get-started">
  ## Pour commencer
</div>

Ce guide explique comment intégrer Auth0, ajouter l’authentification et afficher les renseignements du profil utilisateur dans une application Web Express.js à l’aide du SDK `@auth0/auth0-express`.

<Steps>
  <Step title="Créer un nouveau projet" stepNumber={1}>
    Créez un nouveau répertoire pour votre application Express et initialisez un projet Node.js.

    <AuthCodeGroup>
      ```shellscript Mac theme={null}
      mkdir auth0-express-app && cd auth0-express-app
      npm init -y
      touch server.js .env
      ```

      ```shellscript Windows theme={null}
      mkdir auth0-express-app; cd auth0-express-app
      npm init -y
      New-Item server.js, .env
      ```
    </AuthCodeGroup>

    Mettez à jour votre fichier `package.json` afin d’utiliser les modules ES et d’ajouter des scripts de démarrage :

    ```json theme={null}
    {
      "name": "auth0-express-app",
      "version": "1.0.0",
      "type": "module",
      "main": "server.js",
      "scripts": {
        "start": "node server.js",
        "dev": "node --watch server.js"
      }
    }
    ```
  </Step>

  <Step title="Installer le SDK" stepNumber={2}>
    Installez `@auth0/auth0-express`, ainsi que `express` et `dotenv` :

    ```shell theme={null}
    npm install @auth0/auth0-express@beta express dotenv
    ```
  </Step>

  <Step title="Configurer Auth0" stepNumber={3}>
    Vous devez créer une nouvelle application dans votre tenant Auth0 et configurer vos variables d’environnement.

    <Tabs>
      <Tab title="Configuration rapide">
        <CreateInteractiveApp placeholderText="Express" appType="regular_web" allowedCallbackUrls={["http://localhost:3000/auth/callback"]} allowedLogoutUrls={["http://localhost:3000"]} />

        Une fois votre application créée, ajoutez ces valeurs à votre fichier `.env` :

        <AuthCodeBlock children={envSnippet} language="shellscript" filename=".env" />

        Générez un secret de session sécurisé :

        ```shell theme={null}
        node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
        ```

        Copiez la sortie et utilisez-la comme valeur de `AUTH0_SESSION_SECRET`.

        <Callout icon="file-lines" color="#0EA5E9" iconType="regular">
          Sous macOS ou Linux, vous pouvez aussi exécuter `openssl rand -hex 32`. La commande Node fonctionne sur toutes les plateformes, puisque Node est déjà un prérequis.
        </Callout>
      </Tab>

      <Tab title="CLI">
        Exécutez la commande suivante à la racine de votre projet pour créer une application Auth0 :

        <AuthCodeGroup>
          ```shellscript Mac theme={null}
          AUTH0_APP_NAME="My Express App" && \
          auth0 apps create \
            -n "${AUTH0_APP_NAME}" \
            -t regular \
            --callbacks http://localhost:3000/auth/callback \
            --logout-urls http://localhost:3000 \
            --json | jq -r '"AUTH0_DOMAIN=\(.domain)\nAUTH0_CLIENT_ID=\(.client_id)\nAUTH0_CLIENT_SECRET=\(.client_secret)\nAPP_BASE_URL=http://localhost:3000\nAUTH0_SESSION_SECRET='$(node -e "console.log(require('crypto').randomBytes(32).toString('hex'))")'"' > .env
          ```

          ```powershell Windows theme={null}
          $appName = "My Express App"
          $secret = [System.Convert]::ToBase64String([System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32))
          auth0 apps create -n $appName -t regular `
            --callbacks http://localhost:3000/auth/callback `
            --logout-urls http://localhost:3000 `
            --json | ConvertFrom-Json | ForEach-Object {
              "AUTH0_DOMAIN=$($_.domain)`nAUTH0_CLIENT_ID=$($_.client_id)`nAUTH0_CLIENT_SECRET=$($_.client_secret)`nAPP_BASE_URL=http://localhost:3000`nAUTH0_SESSION_SECRET=$secret"
            } | Out-File .env -Encoding utf8
          ```
        </AuthCodeGroup>

        <Callout icon="file-lines" color="#0EA5E9" iconType="regular">
          Si vous n’avez pas encore installé l’Auth0 CLI, exécutez :

          ```shell theme={null}
          brew tap auth0/auth0-cli && brew install auth0
          ```

          Authentifiez-vous ensuite avec `auth0 login`.
        </Callout>
      </Tab>

      <Tab title="Tableau de bord">
        1. Accédez à [Auth0 Dashboard](https://manage.auth0.com/) → **Applications > Applications**
        2. Sélectionnez **Create Application**
        3. Saisissez un nom (par exemple, "My Express App") et sélectionnez **Regular Web Applications**
        4. Cliquez sur **Create**
        5. Dans l’onglet **Application Settings**, configurez :

        | Champ                 | Valeur                                |
        | --------------------- | ------------------------------------- |
        | Allowed Callback URLs | `http://localhost:3000/auth/callback` |
        | Allowed Logout URLs   | `http://localhost:3000`               |

        6. Cliquez sur **Save Changes**
        7. Copiez votre **Domain**, votre **Client ID** et votre **Client Secret** dans la section **Basic Information**

        Créez votre fichier `.env` :

        <AuthCodeBlock children={envSnippetDashboard} language="shellscript" filename=".env" />

        <Callout icon="file-lines" color="#0EA5E9" iconType="regular">
          Remplacez `YOUR_AUTH0_DOMAIN`, `YOUR_AUTH0_CLIENT_ID` et `YOUR_AUTH0_CLIENT_SECRET` par les valeurs de vos paramètres d’application Auth0.
        </Callout>

        Générez un secret de session sécurisé et remplacez la valeur de l’espace réservé :

        ```shell theme={null}
        node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
        ```

        <Callout icon="file-lines" color="#0EA5E9" iconType="regular">
          Sous macOS ou Linux, vous pouvez aussi exécuter `openssl rand -hex 32`. La commande Node fonctionne sur toutes les plateformes, puisque Node est déjà un prérequis.
        </Callout>
      </Tab>
    </Tabs>
  </Step>

  <Step title="Configurer le middleware" stepNumber={4}>
    Ajoutez le middleware `createAuth0()` à votre application Express. Le SDK configure automatiquement les routes `/auth/login`, `/auth/logout`, `/auth/callback` et `/auth/backchannel-logout`.

    ```javascript server.js theme={null}
    import 'dotenv/config';
    import express from 'express';
    import { createAuth0 } from '@auth0/auth0-express';

    const app = express();
    const port = process.env.PORT || 3000;

    app.use(createAuth0());

    app.get('/', async (req, res) => {
      const session = await req.auth0.client.getSession();
      res.send(session ? 'Logged in' : 'Logged out');
    });

    app.listen(port, () => {
      console.log(`Server running at http://localhost:${port}`);
    });
    ```

    **Ce que cela fait :**

    * `createAuth0()` lit automatiquement les informations d’identification dans les variables d’environnement (`AUTH0_DOMAIN`, `AUTH0_CLIENT_ID`, etc.)
    * Configure quatre routes d’authentification sous `/auth/`
    * Ajoute `req.auth0.client` à chaque requête pour accéder à la session et au jeton
  </Step>

  <Step title="Ajoutez le login, le logout et une route de profil protégée" stepNumber={5}>
    Protégez les routes à l’aide du middleware `requiresAuth` du SDK et affichez les données de profil utilisateur avec `getUser()`.

    ```javascript server.js theme={null}
    import 'dotenv/config';
    import express from 'express';
    import { createAuth0, requiresAuth } from '@auth0/auth0-express';

    const app = express();
    const port = process.env.PORT || 3000;

    app.use(createAuth0());

    // Route d'accueil publique
    app.get('/', async (req, res) => {
      const session = await req.auth0.client.getSession();
      const isAuthenticated = !!session;

      res.send(`
        <html>
          <head>
            <title>Auth0 Express (Beta) Quickstart</title>
            <style>
              body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; padding: 2rem; max-width: 600px; margin: 0 auto; }
              a { color: #0066cc; text-decoration: none; margin-right: 1rem; }
              .status { padding: 1rem; border-radius: 4px; margin: 1rem 0; }
              .logged-in { background: #d4edda; color: #155724; }
              .logged-out { background: #f8d7da; color: #721c24; }
            </style>
          </head>
          <body>
            <h1>Auth0 Express (Beta) Quickstart</h1>
            <div class="status ${isAuthenticated ? 'logged-in' : 'logged-out'}">
              ${isAuthenticated ? '✓ You are logged in' : '✗ You are logged out'}
            </div>
            <nav>
              ${isAuthenticated
                ? '<a href="/profile">Profile</a> | <a href="/auth/logout">Logout</a>'
                : '<a href="/auth/login">Login</a>'}
            </nav>
          </body>
        </html>
      `);
    });

    // Route de profil protégée — requiresAuth redirige les utilisateurs non authentifiés vers /auth/login
    app.get('/profile', requiresAuth(), async (req, res) => {
      const user = await req.auth0.client.getUser();

      res.send(`
        <html>
          <head>
            <title>Profile</title>
            <style>
              body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; padding: 2rem; max-width: 600px; margin: 0 auto; }
              pre { background: #f4f4f4; padding: 1rem; border-radius: 4px; overflow-x: auto; }
              img { border-radius: 50%; }
            </style>
          </head>
          <body>
            <h1>User Profile</h1>
            ${user.picture ? `<img src="${user.picture}" alt="Profile" width="80" />` : ''}
            <h2>${user.name || user.nickname || 'User'}</h2>
            <p><strong>Email:</strong> ${user.email || 'N/A'}</p>
            <h3>Full Profile</h3>
            <pre>${JSON.stringify(user, null, 2)}</pre>
            <a href="/">← Back</a> | <a href="/auth/logout">Logout</a>
          </body>
        </html>
      `);
    });

    app.listen(port, () => {
      console.log(`Server running at http://localhost:${port}`);
    });
    ```

    **Points clés :**

    * `requiresAuth()` de `@auth0/auth0-express` protège les routes — les utilisateurs non authentifiés sont redirigés vers `/auth/login`
    * `req.auth0.client.getUser()` renvoie le profil de l’utilisateur authentifié
    * Le lien de login pointe vers `/auth/login` et celui de logout, vers `/auth/logout` — les deux sont automatiquement montés
  </Step>

  <Step title="Exécutez votre application" stepNumber={6}>
    Démarrez le serveur de développement :

    ```shell theme={null}
    npm run dev
    ```

    Ouvrez votre navigateur à l’adresse [http://localhost:3000](http://localhost:3000).

    <Check>
      **Checkpoint**

      Vous devriez maintenant disposer d’un Login flow Auth0 entièrement fonctionnel. Lorsque vous :

      1. Cliquez sur **Login** — vous êtes redirigé vers la page Universal Login d’Auth0
      2. Terminez l’authentification — vous êtes redirigé vers votre application à `/auth/callback`
      3. Accédez à `/profile` — vous voyez les renseignements sur l’utilisateur
      4. Cliquez sur **Logout** — votre session est supprimée et vous êtes déconnecté d’Auth0
    </Check>
  </Step>
</Steps>

***

<div id="advanced-usage">
  ## Utilisation avancée
</div>

<AccordionGroup>
  <Accordion title="Appeler une API protégée avec un jeton d’accès">
    Configurez le SDK avec une `audience` afin de demander un jeton d’accès pour votre API, puis récupérez-le avec `getAccessToken()`.

    Ajoutez l’audience de votre API au fichier `.env` :

    ```shell .env theme={null}
    AUTH0_AUDIENCE=https://your-api.example.com
    ```

    Récupérez le jeton dans une route protégée :

    ```javascript server.js theme={null}
    app.get('/api-data', requiresAuth(), async (req, res) => {
      const { accessToken } = await req.auth0.client.getAccessToken();

      const response = await fetch('https://your-api.example.com/data', {
        headers: { Authorization: `Bearer ${accessToken}` },
      });

      res.json(await response.json());
    });
    ```

    Le SDK actualise automatiquement le jeton d’accès lorsqu’il expire.
  </Accordion>

  <Accordion title="Utiliser une connexion personnalisée avec returnTo">
    Redirigez les utilisateurs vers une page précise après leur connexion à l’aide du paramètre `returnTo` :

    ```javascript server.js theme={null}
    app.get('/dashboard', async (req, res) => {
      const session = await req.auth0.client.getSession();
      if (!session) {
        return res.redirect('/auth/login?returnTo=/dashboard');
      }
      res.send('Welcome to your dashboard!');
    });
    ```
  </Accordion>

  <Accordion title="Middleware d’autorisation personnalisé">
    Créez votre propre logique d’autorisation à partir de la session :

    ```javascript server.js theme={null}
    async function requireAdmin(req, res, next) {
      const user = await req.auth0.client.getUser();
      if (!user) return res.redirect('/auth/login');
      if (!user['https://myapp.com/roles']?.includes('admin')) {
        return res.status(403).send('Forbidden');
      }
      next();
    }

    app.get('/admin', requireAdmin, (req, res) => {
      res.send('Admin panel');
    });
    ```

    La revendication `https://myapp.com/roles` n’est pas incluse par défaut ; ajoutez-la au jeton d’ID à l’aide d’une [Action](https://auth0.com/docs/customize/actions) et utilisez un nom de revendication avec espace de noms.
  </Accordion>
</AccordionGroup>

***

<div id="troubleshooting">
  ## Dépannage
</div>

<AccordionGroup>
  <Accordion title="'req.auth0 est undefined'">
    **Cause :** Le middleware `createAuth0()` n’a pas été enregistré avant le gestionnaire de votre route.

    **Correctif :** Assurez-vous que `app.use(createAuth0())` figure avant toute route qui accède à `req.auth0` :

    ```javascript theme={null}
    // ✅ Correct
    app.use(createAuth0());
    app.get('/profile', requiresAuth(), handler);

    // ❌ Incorrect
    app.get('/profile', requiresAuth(), handler);
    app.use(createAuth0());
    ```
  </Accordion>

  <Accordion title="Erreur de non-correspondance de l’URL de rappel">
    **Cause :** L’URL de rappel définie dans les paramètres de votre application Auth0 ne correspond pas à `http://localhost:3000/auth/callback`.

    **Correctif :**

    1. Accédez à [Auth0 Dashboard](https://manage.auth0.com/) → **Applications > Applications** → votre application → **Paramètres de l’application**
    2. Ajoutez `http://localhost:3000/auth/callback` aux **URL de rappel autorisées**
    3. Ajoutez `http://localhost:3000` aux **URL de logout autorisées**
    4. Cliquez sur **Enregistrer les modifications**

    Remarque : le SDK `@auth0/auth0-express` utilise `/auth/callback` (et non `/callback`, comme `express-openid-connect`).
  </Accordion>

  <Accordion title="Variables d’environnement non chargées">
    **Cause :** `dotenv/config` n’est pas importé ou le fichier `.env` ne contient pas les valeurs requises.

    **Correctif :**

    1. Assurez-vous que `import 'dotenv/config'` (ou `require('dotenv').config()`) se trouve au début de votre fichier d’entrée
    2. Vérifiez que votre fichier `.env` contient les cinq variables requises : `AUTH0_DOMAIN`, `AUTH0_CLIENT_ID`, `AUTH0_CLIENT_SECRET`, `APP_BASE_URL`, `AUTH0_SESSION_SECRET`
    3. Déboguez les valeurs manquantes :

    ```javascript theme={null}
    console.log({
      domain: !!process.env.AUTH0_DOMAIN,
      clientId: !!process.env.AUTH0_CLIENT_ID,
      clientSecret: !!process.env.AUTH0_CLIENT_SECRET,
      appBaseUrl: !!process.env.APP_BASE_URL,
      sessionSecret: !!process.env.AUTH0_SESSION_SECRET,
    });
    ```
  </Accordion>

  <Accordion title="Erreur « Invalid state » après la connexion">
    **Cause :** Le cookie de session n’est pas correctement défini ou vous accédez directement à l’URL de rappel.

    **Correctif :**

    1. Assurez-vous que `APP_BASE_URL` correspond à l’URL utilisée dans votre navigateur (p. ex., `http://localhost:3000`)
    2. Effacez les cookies de votre navigateur et réessayez
    3. En production, assurez-vous d’utiliser HTTPS
  </Accordion>
</AccordionGroup>

***

<div id="next-steps">
  ## Prochaines étapes
</div>

* **[Protéger une API Express](/docs/fr-ca/quickstart/backend/express-api-beta)** — Utilisez `@auth0/auth0-express-api` pour valider les jetons d’accès dans votre API
* **[Ajouter l’autorisation](https://auth0.com/docs/manage-users/access-control/rbac)** — Mettez en œuvre le contrôle d’accès basé sur les rôles
* **[Personnaliser Universal Login](https://auth0.com/docs/customize/universal-login-pages)** — Personnalisez l’image de marque de votre expérience de connexion
* **[Ajouter des connexions sociales](https://auth0.com/docs/connections/social)** — Activez Google, GitHub et d’autres connexions sociales
* **[Mettre en œuvre l’AMF](https://auth0.com/docs/secure/multi-factor-authentication)** — Ajoutez l’authentification multifacteur

***

<div id="resources">
  ## Ressources
</div>

* **[auth0/auth0-express GitHub](https://github.com/auth0/auth0-express/tree/main/packages/auth0-express)** — Code source et exemples
* **[Auth0 Community](https://community.auth0.com/)** — Obtenez de l’aide auprès de la communauté
