> ## 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 connexion à votre application Fastify

> Ce guide montre comment intégrer Auth0, ajouter l’authentification et afficher les informations du profil utilisateur dans une application Web Fastify à l’aide du SDK Fastify d’Auth0.

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

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) + "*****MASKED*****";
          }
          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 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 requis");
        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 de l'application :", 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 application Auth0</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 />;
};

<HowToSchema />

export function generateRandomString(length) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  return Array.from({
    length
  }, () => chars[Math.floor(Math.random() * chars.length)]).join('');
}

export const localEnvSnippet = `AUTH0_DOMAIN={yourDomain}
AUTH0_CLIENT_ID={yourClientId}
AUTH0_CLIENT_SECRET={yourClientSecret}
SESSION_SECRET=${generateRandomString(64)}
APP_BASE_URL=http://localhost:3000`;

<Accordion title="Utiliser l’IA pour intégrer Auth0" icon="microchip-ai" iconType="solid" defaultOpen>
  Si vous utilisez un assistant de codage IA comme Claude Code, Cursor ou GitHub Copilot, vous pouvez ajouter automatiquement l’authentification Auth0 en quelques minutes à l’aide des [agent skills](https://agentskills.io/home).

  **Installer :**

  ```bash theme={null}
  npx skills add auth0/agent-skills --skill auth0-quickstart --skill auth0-fastify
  ```

  **Ensuite, demandez à votre assistant IA :**

  ```text theme={null}
  Add Auth0 authentication to my Fastify app
  ```

  Votre assistant IA créera automatiquement votre application Auth0, récupérera les identifiants, installera `@auth0/auth0-fastify`, configurera le plugin et créera toutes les routes et vues nécessaires. [Documentation complète des agent skills →](/fr-CA/docs/quickstart/agent-skills)
</Accordion>

<Note>
  **Prérequis :** Avant de commencer, assurez-vous d’avoir installé les éléments suivants :

  * **[Node.js](https://nodejs.org/en/download)** 20 LTS ou une version ultérieure
  * **[npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)** 10+ ou **[yarn](https://classic.yarnpkg.com/lang/en/docs/install/)** 1.22+ ou **[pnpm](https://pnpm.io/installation)** 8+

  Vérifiez l’installation : `node --version && npm --version`

  **Compatibilité des versions de Fastify :** Ce guide de démarrage rapide fonctionne avec **Fastify 5.x** et les versions ultérieures.
</Note>

<div id="get-started">
  ## Premiers pas
</div>

Ce guide de démarrage rapide explique comment intégrer l’authentification Auth0 à une application Fastify. Vous créerez une application web sécurisée avec des fonctionnalités de connexion, de déconnexion et de profil utilisateur à l’aide du SDK Fastify d’Auth0.

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

    ```shellscript theme={null}
    mkdir auth0-fastify && cd auth0-fastify
    ```

    Initialisez le projet

    ```shellscript theme={null}
    npm init -y
    ```

    Créez la structure du projet

    ```shellscript theme={null}
    touch server.js .env
    ```
  </Step>

  <Step title="Installer le SDK Auth0 pour Fastify" stepNumber={2}>
    Installez les dépendances requises

    ```shellscript theme={null}
    npm install @auth0/auth0-fastify fastify dotenv @fastify/view ejs
    ```

    <Info>
      Nous utilisons `@fastify/view` avec `ejs` pour le rendu côté serveur. Vous pouvez utiliser n’importe quel moteur de modèles pris en charge par Fastify.
    </Info>

    Mettez à jour votre `package.json` pour y ajouter des scripts de démarrage :

    ```json package.json theme={null}
    {
      "name": "auth0-fastify",
      "version": "1.0.0",
      "type": "module",
      "main": "server.js",
      "scripts": {
        "start": "node server.js",
        "dev": "node --watch server.js"
      },
      "dependencies": {
        "@auth0/auth0-fastify": "^1.2.0",
        "@fastify/view": "^10.0.0",
        "dotenv": "^16.3.1",
        "ejs": "^3.1.9",
        "fastify": "^5.0.0"
      }
    }
    ```
  </Step>

  <Step title="Configurez votre application Auth0" stepNumber={3}>
    Ensuite, vous devez créer une nouvelle application dans votre locataire Auth0 et ajouter les variables d’environnement à votre projet.

    Vous avez trois options pour configurer votre application Auth0 : utiliser l’outil de configuration rapide (recommandé), exécuter une commande CLI ou faire la configuration manuellement dans l’Auth0 Dashboard :

    <Tabs>
      <Tab title="Configuration rapide (recommandée)">
        Créez une application Auth0 et copiez le fichier `.env` prérempli avec les bonnes valeurs de configuration.

        <CreateInteractiveApp placeholderText="Fastify" appType="regular_web" allowedCallbackUrls={["http://localhost:3000/auth/callback"]} allowedLogoutUrls={["http://localhost:3000"]} />

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

      <Tab title="CLI">
        Exécutez la commande suivante à la racine de votre projet pour créer une application Auth0 et générer un fichier `.env` :

        <CodeGroup>
          ```shellscript Mac theme={null}
          # Installer Auth0 CLI (si ce n’est pas déjà fait)
          brew tap auth0/auth0-cli && brew install auth0

          # Configurer l’application Auth0 et générer le fichier .env
          auth0 qs setup --app --type regular --framework fastify --name "My Fastify App" --port 3000
          ```

          ```powershell Windows theme={null}
          # Installer Auth0 CLI (si ce n’est pas déjà fait)
          scoop bucket add auth0 https://github.com/auth0/scoop-auth0-cli.git
          scoop install auth0

          # Configurer l’application Auth0 et générer le fichier .env
          auth0 qs setup --app --type regular --framework fastify --name "My Fastify App" --port 3000
          ```
        </CodeGroup>

        <Note>
          Cette commande permet de :

          1. Vérifier si vous êtes authentifié (et vous inviter à vous connecter au besoin)
          2. Créer une application Web standard Auth0 configurée pour `http://localhost:3000`
          3. Générer un fichier `.env` contenant `AUTH0_DOMAIN`, `AUTH0_CLIENT_ID`, `AUTH0_CLIENT_SECRET`, `SESSION_SECRET` et `APP_BASE_URL`
        </Note>
      </Tab>

      <Tab title="Auth0 Dashboard">
        1. Accédez à [l’Auth0 Dashboard](https://manage.auth0.com/dashboard/)
        2. Allez à **Applications** → **Create Application**
        3. Entrez un nom pour votre application (par ex., "My Fastify App")
        4. Sélectionnez **Regular Web Applications** et cliquez sur **Create**
        5. Dans l’onglet **Settings**, configurez les éléments suivants :

        | Paramètre             | Valeur                                |
        | --------------------- | ------------------------------------- |
        | Allowed Callback URLs | `http://localhost:3000/auth/callback` |
        | Allowed Logout URLs   | `http://localhost:3000`               |

        6. Faites défiler la page vers le bas et cliquez sur **Save Changes**
        7. Copiez les valeurs **Domaine**, **ID client** et **Secret client** de la section **Basic Information**

        Créez votre fichier `.env` avec les valeurs suivantes :

        ```bash .env theme={null}
        AUTH0_DOMAIN=YOUR_AUTH0_DOMAIN
        AUTH0_CLIENT_ID=YOUR_CLIENT_ID
        AUTH0_CLIENT_SECRET=YOUR_CLIENT_SECRET
        SESSION_SECRET=use-a-long-random-string-at-least-64-characters
        APP_BASE_URL=http://localhost:3000
        ```

        <Warning>
          Remplacez `YOUR_AUTH0_DOMAIN` par le domaine de votre locataire Auth0 (par ex., `dev-abc123.us.auth0.com`), `YOUR_CLIENT_ID` par l’ID client de votre application et `YOUR_CLIENT_SECRET` par le Secret client de votre application dans l’Auth0 Dashboard.
        </Warning>

        Générez un secret sécurisé pour le chiffrement de la session :

        ```bash theme={null}
        openssl rand -hex 64
        ```

        Copiez le résultat et utilisez-le comme valeur de `SESSION_SECRET` dans votre fichier `.env`.
      </Tab>
    </Tabs>

    <Tip>
      Vérifiez que votre fichier `.env` existe : `cat .env` (Mac/Linux) ou `type .env` (Windows)
    </Tip>
  </Step>

  <Step title="Configurer le plugiciel Auth0" stepNumber={4}>
    Créez votre serveur Fastify et enregistrez le module d’extension Auth0 :

    ```javascript server.js {1-4,7-8,11-18,21-22} lines theme={null}
    import 'dotenv/config';
    import Fastify from 'fastify';
    import fastifyView from '@fastify/view';
    import fastifyAuth0 from '@auth0/auth0-fastify';
    import ejs from 'ejs';

    const fastify = Fastify({ logger: true });
    const port = process.env.PORT || 3000;

    // Enregistrer le moteur de vue
    await fastify.register(fastifyView, {
      engine: { ejs },
      root: './views',
    });

    // Enregistrer le plugin Auth0
    await fastify.register(fastifyAuth0, {
      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.SESSION_SECRET,
    });

    // Démarrer le serveur
    fastify.listen({ port }, (err) => {
      if (err) {
        fastify.log.error(err);
        process.exit(1);
      }
      fastify.log.info(`Server running at http://localhost:${port}`);
    });
    ```

    **Ce que cela fait :**

    * Enregistre le moteur de vues pour le rendu de modèles HTML
    * Configure le plugin Auth0 avec vos identifiants
    * Crée automatiquement des routes sur `/auth/login`, `/auth/logout` et `/auth/callback`
    * Gère les sessions à l’aide de témoins chiffrés
  </Step>

  <Step title="Créer des gabarits de vue" stepNumber={5}>
    Créez un répertoire `views` et ajoutez des fichiers de gabarit :

    ```shellscript Mac/Linux theme={null}
    mkdir views && touch views/home.ejs views/profile.ejs
    ```

    ```powershell Windows theme={null}
    New-Item -ItemType Directory -Path views
    New-Item -ItemType File -Path views/home.ejs
    New-Item -ItemType File -Path views/profile.ejs
    ```

    Créez le modèle de page d'accueil :

    ```html views/home.ejs expandable lines theme={null}
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Auth0 Fastify Quickstart</title>
      <style>
        body {
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          margin: 0;
          padding: 2rem;
          min-height: 100vh;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .container {
          background: white;
          border-radius: 20px;
          box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
          padding: 3rem;
          max-width: 500px;
          width: 100%;
          text-align: center;
        }
        h1 {
          color: #2d3748;
          font-size: 2.5rem;
          margin-bottom: 1rem;
        }
        .status {
          padding: 1rem;
          border-radius: 10px;
          margin: 1.5rem 0;
          font-size: 1.1rem;
        }
        .logged-in {
          background: #d4edda;
          color: #155724;
        }
        .logged-out {
          background: #f8d7da;
          color: #721c24;
        }
        .button {
          display: inline-block;
          padding: 1rem 2rem;
          margin: 0.5rem;
          border-radius: 10px;
          text-decoration: none;
          font-weight: 600;
          transition: all 0.3s;
        }
        .button-primary {
          background: #667eea;
          color: white;
        }
        .button-primary:hover {
          background: #5568d3;
          transform: translateY(-2px);
        }
        .button-secondary {
          background: #e53e3e;
          color: white;
        }
        .button-secondary:hover {
          background: #c53030;
          transform: translateY(-2px);
        }
      </style>
    </head>
    <body>
      <div class="container">
        <h1>🚀 Auth0 Fastify</h1>
        <div class="status <%= isAuthenticated ? 'logged-in' : 'logged-out' %>">
          <%= isAuthenticated ? '✓ You are logged in' : '✗ You are logged out' %>
        </div>
        <div>
          <% if (isAuthenticated) { %>
            <a href="/profile" class="button button-primary">View Profile</a>
            <a href="/auth/logout" class="button button-secondary">Logout</a>
          <% } else { %>
            <a href="/auth/login" class="button button-primary">Login</a>
          <% } %>
        </div>
      </div>
    </body>
    </html>
    ```

    Créez le modèle de page de profil :

    ```html views/profile.ejs expandable lines theme={null}
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Profile - Auth0 Fastify</title>
      <style>
        body {
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          margin: 0;
          padding: 2rem;
          min-height: 100vh;
        }
        .container {
          background: white;
          border-radius: 20px;
          box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
          padding: 3rem;
          max-width: 700px;
          margin: 0 auto;
        }
        h1 {
          color: #2d3748;
          margin-bottom: 2rem;
        }
        .profile-card {
          display: flex;
          align-items: center;
          gap: 2rem;
          padding: 2rem;
          background: #f7fafc;
          border-radius: 15px;
          margin-bottom: 2rem;
        }
        .profile-picture {
          width: 100px;
          height: 100px;
          border-radius: 50%;
          object-fit: cover;
          border: 3px solid #667eea;
        }
        .profile-info h2 {
          margin: 0 0 0.5rem 0;
          color: #2d3748;
        }
        .profile-info p {
          margin: 0;
          color: #718096;
        }
        .user-data {
          background: #f7fafc;
          padding: 1.5rem;
          border-radius: 10px;
          overflow-x: auto;
        }
        pre {
          margin: 0;
          white-space: pre-wrap;
          word-wrap: break-word;
        }
        .button {
          display: inline-block;
          padding: 0.75rem 1.5rem;
          margin-right: 1rem;
          border-radius: 10px;
          text-decoration: none;
          font-weight: 600;
          transition: all 0.3s;
        }
        .button-primary {
          background: #667eea;
          color: white;
        }
        .button-primary:hover {
          background: #5568d3;
        }
        .button-secondary {
          background: #e53e3e;
          color: white;
        }
        .button-secondary:hover {
          background: #c53030;
        }
      </style>
    </head>
    <body>
      <div class="container">
        <h1>User Profile</h1>
        <div class="profile-card">
          <img src="<%= user.picture || 'https://via.placeholder.com/100' %>" alt="Profile" class="profile-picture">
          <div class="profile-info">
            <h2><%= user.name || user.nickname || 'User' %></h2>
            <p><strong>Email:</strong> <%= user.email || 'N/A' %></p>
          </div>
        </div>
        <h3>Full User Object</h3>
        <div class="user-data">
          <pre><%= JSON.stringify(user, null, 2) %></pre>
        </div>
        <div style="margin-top: 2rem;">
          <a href="/" class="button button-primary">← Back to Home</a>
          <a href="/auth/logout" class="button button-secondary">Logout</a>
        </div>
      </div>
    </body>
    </html>
    ```
  </Step>

  <Step title="Créer des routes" stepNumber={6}>
    Ajoutez des routes à votre fichier `server.js` :

    ```javascript server.js expandable lines theme={null}
    import 'dotenv/config';
    import Fastify from 'fastify';
    import fastifyView from '@fastify/view';
    import fastifyAuth0 from '@auth0/auth0-fastify';
    import ejs from 'ejs';

    const fastify = Fastify({ logger: true });
    const port = process.env.PORT || 3000;

    // Enregistrer le moteur de vue
    await fastify.register(fastifyView, {
      engine: { ejs },
      root: './views',
    });

    // Enregistrer le plugin Auth0
    await fastify.register(fastifyAuth0, {
      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.SESSION_SECRET,
    });

    // Route d'accueil - publique
    fastify.get('/', async (request, reply) => {
      const session = await fastify.auth0Client.getSession({ request, reply });
      return reply.view('views/home.ejs', {
        isAuthenticated: !!session,
      });
    });

    // Route de profil - protégée
    fastify.get('/profile', {
      preHandler: async (request, reply) => {
        const session = await fastify.auth0Client.getSession({ request, reply });
        if (!session) {
          return reply.redirect('/auth/login');
        }
      }
    }, async (request, reply) => {
      const user = await fastify.auth0Client.getUser({ request, reply });
      return reply.view('views/profile.ejs', { user });
    });

    // Démarrer le serveur
    fastify.listen({ port }, (err) => {
      if (err) {
        fastify.log.error(err);
        process.exit(1);
      }
      fastify.log.info(`Server running at http://localhost:${port}`);
    });
    ```

    **Points clés :**

    * La route d’accueil vérifie le statut d’authentification et le transmet au gabarit
    * La route de profil utilise un `preHandler` pour la protéger
    * `getSession()` renvoie la session de l’utilisateur ou `null` s’il n’est pas authentifié
    * `getUser()` renvoie les informations du profil de l’utilisateur authentifié
  </Step>

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

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

    Ouvrez [http://localhost:3000](http://localhost:3000) dans votre navigateur.

    <Info>
      L’option `--watch` de Node.js 20+ redémarre automatiquement le serveur lorsque des fichiers sont modifiés.
    </Info>
  </Step>
</Steps>

<Check>
  **Vérification**

  Vous devriez maintenant avoir une page de connexion à Auth0 entièrement fonctionnelle. 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
  3. Visitez "/profile" - vous voyez les informations de votre profil
  4. Cliquez sur "Logout" - vous êtes déconnecté à la fois de votre application et d’Auth0
</Check>

***

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

<Accordion title="Appeler des API protégées avec des jetons d’accès">
  Pour appeler des API externes qui nécessitent un jeton d’accès, configurez le SDK avec une audience :

  ```javascript server.js theme={null}
  await fastify.register(fastifyAuth0, {
    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.SESSION_SECRET,
    audience: process.env.AUTH0_AUDIENCE, // Ajoutez ceci
  });
  ```

  Ajoutez ceci à votre fichier `.env` :

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

  Ensuite, récupérez et utilisez le jeton d’accès :

  ```javascript server.js theme={null}
  fastify.get('/api-data', {
    preHandler: async (request, reply) => {
      const session = await fastify.auth0Client.getSession({ request, reply });
      if (!session) {
        return reply.redirect('/auth/login');
      }
    }
  }, async (request, reply) => {
    try {
      const { accessToken } = await fastify.auth0Client.getAccessToken({ request, reply });

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

      const data = await response.json();
      return data;
    } catch (error) {
      fastify.log.error('API call failed:', error);
      return reply.status(500).send({ error: 'Failed to fetch data' });
    }
  });
  ```
</Accordion>

<Accordion title="Chemins de route personnalisés">
  Par défaut, les routes Auth0 sont montées sous `/auth/*`. Vous pouvez désactiver le montage automatique et créer des routes personnalisées :

  ```javascript server.js theme={null}
  await fastify.register(fastifyAuth0, {
    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.SESSION_SECRET,
    mountRoutes: false, // Désactiver le montage automatique
  });

  // Route de connexion personnalisée
  fastify.get('/custom-login', async (request, reply) => {
    const authorizationUrl = await fastify.auth0Client.startInteractiveLogin(
      {
        authorizationParams: {
          redirect_uri: `${process.env.APP_BASE_URL}/custom-callback`
        }
      },
      { request, reply }
    );
    return reply.redirect(authorizationUrl.href);
  });

  // Route de callback personnalisée
  fastify.get('/custom-callback', async (request, reply) => {
    await fastify.auth0Client.completeInteractiveLogin(
      new URL(request.url, process.env.APP_BASE_URL),
      { request, reply }
    );
    return reply.redirect('/');
  });

  // Route de déconnexion personnalisée
  fastify.get('/custom-logout', async (request, reply) => {
    const logoutUrl = await fastify.auth0Client.logout(
      { returnTo: process.env.APP_BASE_URL },
      { request, reply }
    );
    return reply.redirect(logoutUrl.href);
  });
  ```

  <Note>
    N’oubliez pas de mettre à jour vos **Allowed Callback URLs** dans Auth0 Dashboard pour inclure votre URL de callback personnalisée.
  </Note>
</Accordion>

<Accordion title="Liaison de comptes">
  Permettez aux utilisateurs de lier plusieurs fournisseurs d’authentification à un même compte :

  ```javascript server.js theme={null}
  await fastify.register(fastifyAuth0, {
    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.SESSION_SECRET,
    mountConnectRoutes: true, // Activer les routes de liaison de comptes
  });
  ```

  Cela crée automatiquement les routes suivantes :

  * `/auth/connect` - Lier un nouveau fournisseur
  * `/auth/connect/callback` - Gérer le callback de liaison
  * `/auth/unconnect` - Dissocier un fournisseur
  * `/auth/unconnect/callback` - Gérer le callback de dissociation

  Ajoutez des boutons de liaison à votre page de profil :

  ```html views/profile.ejs theme={null}
  <div>
    <a href="/auth/connect?connection=google-oauth2">Lier le compte Google</a>
    <a href="/auth/unconnect?connection=google-oauth2">Dissocier le compte Google</a>
  </div>
  ```
</Accordion>

<Accordion title="Utilisation de TypeScript">
  Convertissez votre projet en TypeScript pour améliorer la sécurité des types :

  ```bash theme={null}
  npm install --save-dev typescript @types/node tsx
  ```

  Créez un `tsconfig.json` :

  ```json tsconfig.json theme={null}
  {
    "compilerOptions": {
      "target": "ES2022",
      "module": "ESNext",
      "moduleResolution": "node",
      "esModuleInterop": true,
      "strict": true,
      "skipLibCheck": true,
      "outDir": "./dist"
    },
    "include": ["src/**/*"],
    "exclude": ["node_modules"]
  }
  ```

  Renommez `server.js` en `server.ts` et ajoutez les types :

  ```typescript server.ts theme={null}
  import 'dotenv/config';
  import Fastify, { FastifyRequest, FastifyReply } from 'fastify';
  import fastifyView from '@fastify/view';
  import fastifyAuth0 from '@auth0/auth0-fastify';
  import ejs from 'ejs';

  const fastify = Fastify({ logger: true });
  const port = process.env.PORT || 3000;

  await fastify.register(fastifyView, {
    engine: { ejs },
    root: './views',
  });

  await fastify.register(fastifyAuth0, {
    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.SESSION_SECRET!,
  });

  fastify.get('/', async (request: FastifyRequest, reply: FastifyReply) => {
    const session = await fastify.auth0Client.getSession({ request, reply });
    return reply.view('views/home.ejs', {
      isAuthenticated: !!session,
    });
  });

  fastify.listen({ port: Number(port) });
  ```

  Mettez à jour `package.json` :

  ```json package.json theme={null}
  {
    "scripts": {
      "dev": "tsx watch server.ts",
      "build": "tsc",
      "start": "node dist/server.js"
    }
  }
  ```
</Accordion>

***

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

<AccordionGroup>
  <Accordion title="Problèmes courants et solutions">
    ### Erreur « Invalid state » après la connexion

    **Problème :** Le `state` ne correspond pas entre la requête d'authentification et le callback.

    **Solutions :**

    1. Assurez-vous que les témoins sont bien définis (et non bloqués par le navigateur)
    2. Vérifiez que l'URL de callback correspond exactement dans Auth0 Dashboard (y compris `/auth/callback`)
    3. Vérifiez que `SESSION_SECRET` est défini et contient au moins 64 caractères

    ### Erreur « session is undefined »

    **Problème :** Impossible de récupérer les données de session.

    **Solution :** Assurez-vous que le plugin Auth0 est enregistré avant d'accéder aux méthodes de session :

    ```javascript theme={null}
    // ✅ Bon ordre
    await fastify.register(fastifyAuth0, { ... });
    fastify.get('/profile', async (request, reply) => {
      const session = await fastify.auth0Client.getSession({ request, reply });
    });

    // ❌ Incorrect - await n'est pas utilisé pour le plugin
    fastify.register(fastifyAuth0, { ... }); // await manquant
    fastify.get('/profile', async (request, reply) => { ... });
    ```

    ### Non-correspondance de l'URL de callback

    **Problème :** Erreur « Callback URL mismatch » provenant d'Auth0.

    **Solution :**

    1. Accédez à Auth0 Dashboard → Applications → votre application → Settings
    2. Ajoutez `http://localhost:3000/auth/callback` à **Allowed Callback URLs**
    3. L'URL doit correspondre exactement (y compris le chemin `/auth/callback`)

    ### Les variables d'environnement ne se chargent pas

    **Problème :** Les valeurs de configuration sont `undefined`.

    **Solution :**

    1. Assurez-vous que `import 'dotenv/config'` se trouve en haut de votre fichier d'entrée
    2. Vérifiez que le fichier `.env` se trouve dans le répertoire racine
    3. Vérifiez qu'il n'y a pas de fautes de frappe dans les noms de variables

    ```javascript theme={null}
    // Débogage : afficher les valeurs de configuration (à retirer en production !)
    console.log('Config check:', {
      hasDomain: !!process.env.AUTH0_DOMAIN,
      hasClientID: !!process.env.AUTH0_CLIENT_ID,
      hasSecret: !!process.env.SESSION_SECRET,
    });
    ```
  </Accordion>
</AccordionGroup>

***

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

Maintenant que l’authentification fonctionne, pensez à explorer :

* **[Authentification d’API avec Fastify](/fr-CA/docs/quickstart/backend/fastify)** - Protégez les points de terminaison de votre API à l’aide de la validation JWT
* **[Personnaliser Universal Login](https://auth0.com/docs/customize/universal-login-pages)** - Personnalisez votre expérience de connexion
* **[Ajouter des connexions sociales](https://auth0.com/docs/connections/social)** - Activez Google, GitHub et d’autres connexions sociales
* **[Implémenter MFA](https://auth0.com/docs/secure/multi-factor-authentication)** - Ajoutez l’authentification multifacteur

***

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

* **[auth0-fastify GitHub](https://github.com/auth0/auth0-fastify)** - Code source et exemples
* **[Documentation Fastify](https://fastify.dev/)** - En savoir plus sur Fastify
* **[Communauté Auth0](https://community.auth0.com/)** - Obtenez de l’aide auprès de la communauté
