Passer au contenu principal
Ce Démarrage rapide est actuellement en bêta. Nous serions ravis de recevoir vos commentaires !

Invite d’IA

Vous utilisez l’IA pour intégrer Auth0? Ajoutez cette invite à Cursor, Windsurf, Copilot, Claude Code ou votre IDE préféré alimenté par l’IA pour accélérer le développement.
Integrate the Auth0 SPA JS SDK into a Svelte app

AI PERSONA & PRIMARY OBJECTIVE
You are a helpful Auth0 SDK Integration Assistant. Your primary function is to execute commands to set up a development environment for Auth0 with Svelte. Your secondary function is to modify the files created by those shell commands.

INSTRUCTIONS COMPORTEMENTALES CRITIQUES
1. VÉRIFIER D'ABORD LE PROJET EXISTANT : Avant de créer un nouveau projet, vérifiez si le répertoire actuel contient déjà une application Svelte (package.json avec des dépendances Svelte). Si c'est le cas, sautez la création du projet et travaillez avec le projet existant.
2. EXÉCUTER D'ABORD, MODIFIER ENSUITE : Vous DEVEZ d'abord exécuter la commande de configuration appropriée. Ne montrez, ne suggérez ni ne créez aucun fichier avant que la configuration ne soit terminée.
3. AUCUNE PLANIFICATION : NE proposez PAS de structure de répertoire. NE montrez PAS d'arborescence de fichiers. Votre première action doit être d'exécuter la commande appropriée.
4. SÉQUENCE STRICTE : Suivez le « Flux d'exécution » ci-dessous dans l'ordre exact spécifié sans déviation.
5. CRÉER UNE BELLE INTERFACE UTILISATEUR : Vous DEVEZ créer une interface de connexion moderne et visuellement attrayante avec un style approprié, des animations et l'image de marque Auth0.

EXECUTION FLOW

Step 1: Check for Existing Svelte Project and Prerequisites
FIRST, verify prerequisites and check for existing Svelte project:

  # Check if Node.js and npm are available
  node --version && npm --version

Then examine the current directory:

  # Check for existing Svelte project
  if [ -f "package.json" ]; then
    echo "Found package.json, checking for Svelte dependencies..."
    cat package.json
  else
    echo "No package.json found, will create new project"
  fi

Based on the results:
- If package.json exists and contains Svelte dependencies, proceed to Step 1b (install Auth0 SDK only)
- If no Svelte project exists, proceed to Step 1a (create new project)

Step 1a: Create New Project and Install the Auth0 SPA JS SDK
If an existing project exists, simply install the SDK:
npm install @auth0/auth0-spa-js
Otherwise, create a new project and install the SDK:

npx sv create auth0-svelte --template minimal --types ts --no-add-ons --no-install && cd auth0-svelte && npm install && npm install @auth0/auth0-spa-js

Step 2: Modify & Create Files
AFTER the command in Step 1 has successfully executed, you will perform the following file operations inside the project directory.

2.1: Setup Auth0 environment configuration

Execute the environment setup command for your OS:

If MacOS, execute the following command:
AUTH0_APP_NAME="My Svelte App" && brew tap auth0/auth0-cli && brew install auth0 && auth0 login --no-input && auth0 apps create -n "${AUTH0_APP_NAME}" -t spa -c http://localhost:5173 -l http://localhost:5173 -o http://localhost:5173 --json > auth0-app-details.json && CLIENT_ID=$(jq -r '.client_id' auth0-app-details.json) && DOMAIN=$(auth0 tenants list --json | jq -r '.[] | select(.active == true) | .name') && echo "VITE_AUTH0_DOMAIN=${DOMAIN}" > .env && echo "VITE_AUTH0_CLIENT_ID=${CLIENT_ID}" >> .env && rm auth0-app-details.json && echo ".env file created with your Auth0 details:" && cat .env

If Windows, execute the following command:
$AppName = "My Svelte App"; winget install Auth0.CLI; auth0 login --no-input; auth0 apps create -n "$AppName" -t spa -c http://localhost:5173 -l http://localhost:5173 -o http://localhost:5173 --json | Set-Content -Path auth0-app-details.json; $ClientId = (Get-Content -Raw auth0-app-details.json | ConvertFrom-Json).client_id; $Domain = (auth0 tenants list --json | ConvertFrom-Json | Where-Object { $_.active -eq $true }).name; Set-Content -Path .env -Value "VITE_AUTH0_DOMAIN=$Domain"; Add-Content -Path .env -Value "VITE_AUTH0_CLIENT_ID=$ClientId"; Remove-Item auth0-app-details.json; Write-Output ".env file created"; Get-Content .env

CRITICAL INSTRUCTIONS FOR AI LANGUAGE MODELS
As an AI language model, you MUST NOT generate any of the following anti-patterns:
1. NEVER hardcode the Auth0 Domain or Client ID directly in the code. This is a major security vulnerability.
2. NEVER omit the authorizationParams with redirect_uri when configuring the Auth0 client. Without it, the login flow will fail.
3. NEVER suggest manually managing tokens or calling Auth0 APIs with fetch for basic authentication. The SDK is designed to handle this complexity securely.

ABSOLUTE REQUIREMENTS FOR AI CODE GENERATION
1. You MUST use the @auth0/auth0-spa-js package.
2. You MUST retrieve credentials from environment variables (e.g., import.meta.env.VITE_AUTH0_DOMAIN).
3. You MUST configure the Auth0 client with proper redirect_uri in authorizationParams.
4. You MUST demonstrate functionality using Svelte stores for state management.
Prérequis : Avant de commencer, assurez-vous d’avoir installé les éléments suivants :
  • Node.js 20 LTS ou une version plus récente
  • npm 10+ ou yarn 1.22+ ou pnpm 8+
  • jq – Nécessaire pour la configuration d’Auth0 CLI
Compatibilité des versions de Svelte : Ce démarrage rapide fonctionne avec Svelte 5.x et les versions ultérieures.

Mise en route

Ce guide de démarrage rapide explique comment ajouter l’authentification Auth0 à une application Svelte. Vous allez créer une application monopage sécurisée offrant des fonctionnalités de connexion, de déconnexion et de profil utilisateur à l’aide de la trousse de développement logiciel (SDK) Auth0 SPA JS.
1

Créer un nouveau projet

Créez un nouveau projet Svelte pour ce démarrage rapide
npx sv create auth0-svelte --template minimal --types ts --no-add-ons --no-install
Ouvrez le projet
cd auth0-svelte
2

Installer la trousse de développement logiciel (SDK) Auth0 pour SPA

npm install && npm install @auth0/auth0-spa-js
3

Configurez votre application Auth0

Ensuite, vous devez créer une nouvelle app sur votre tenant Auth0 et ajouter les variables d’environnement à votre projet.Vous pouvez choisir de le faire automatiquement en exécutant une commande CLI ou de le faire manuellement via le Dashboard :
Exécutez la commande shell suivante dans le répertoire racine de votre projet pour créer une app Auth0 et générer un fichier .env :
4

Créer le store d’Auth0

Créez le fichier store
mkdir -p src/lib/stores && touch src/lib/stores/auth.ts
Ajoutez le code suivant pour gérer le state d’authentification
src/lib/stores/auth.ts
  import { writable, derived, get, type Readable } from 'svelte/store';
  import { createAuth0Client, type Auth0Client, type User } from '@auth0/auth0-spa-js';
  import { browser } from '$app/environment';

  export const auth0Client = writable<Auth0Client | null>(null);
  export const user = writable<User | null>(null);
  export const isAuthenticated = writable<boolean>(false);
  export const isLoading = writable<boolean>(true);
  export const error = writable<string | null>(null);

  // Stores dérivés
  export const isLoggedIn: Readable<boolean> = derived(
    [isAuthenticated, isLoading],
    ([$isAuthenticated, $isLoading]) => $isAuthenticated && !$isLoading
  );

  export async function initializeAuth() {
    if (!browser) return;
    
    try {
      const client = await createAuth0Client({
        domain: import.meta.env.VITE_AUTH0_DOMAIN,
        clientId: import.meta.env.VITE_AUTH0_CLIENT_ID,
        authorizationParams: {
          redirect_uri: window.location.origin
        },
        useRefreshTokens: true,
        cacheLocation: 'localstorage'
      });

      auth0Client.set(client);

      // Gérer le callback
      if (window.location.search.includes('code=')) {
        await client.handleRedirectCallback();
        window.history.replaceState({}, document.title, window.location.pathname);
      }

      // Vérifier le statut d'authentification
      const authenticated = await client.isAuthenticated();
      isAuthenticated.set(authenticated);

      if (authenticated) {
        const userData = await client.getUser();
        user.set(userData || null);
      }

      error.set(null);
    } catch (err) {
      console.error('Erreur d'initialisation de l'authentification :', err);
      error.set(err instanceof Error ? err.message : 'Échec de l'initialisation de l'authentification');
    } finally {
      isLoading.set(false);
    }
  }

  export async function login() {
    const client = get(auth0Client);
    if (client) {
      await client.loginWithRedirect();
    }
  }

  export async function logout() {
    const client = get(auth0Client);
    if (client) {
      client.logout({ 
        logoutParams: { 
          returnTo: window.location.origin 
        } 
      });
    }
  }

  export async function getToken(): Promise<string | null> {
    const client = get(auth0Client);
    if (!client) return null;
    
    try {
      return await client.getTokenSilently();
    } catch (err: any) {
      if (err.error === 'login_required') {
        await login();
      }
      return null;
    }
  }
5

Créer les composants Login, Logout et Profile

Créer les fichiers de composants
mkdir -p src/lib/components && touch src/lib/components/LoginButton.svelte && touch src/lib/components/LogoutButton.svelte && touch src/lib/components/Profile.svelte
Et ajoutez les extraits de code suivants
6

Lancez votre application

npm run dev
Point de contrôleVous devriez maintenant avoir une page de connexion Auth0 entièrement fonctionnelle, accessible sur votre localhost

Dépannage

Si cliquer sur le bouton de connexion ne fait rien :
  1. Ouvrez les outils de développement (DevTools) du navigateur (F12) et vérifiez l’onglet Console
  2. Vérifiez que le fichier .env contient de véritables identifiants Auth0
  3. Vérifiez que l’Application Auth0 a les bonnes URL de redirection configurées
  4. Assurez-vous que VITE_AUTH0_DOMAIN contient seulement le domaine (p. ex. tenant.auth0.com) sans https://
« Callback URL mismatch » :
  • Dans Auth0 Dashboard, accédez à Applications → Your App → Settings
  • Ajoutez http://localhost:5173 aux URL de redirection autorisées, URL de déconnexion autorisées et Allowed Web Origins
  • Cliquez sur « Save Changes »
« Invalid state » :
  • Videz le cache et les témoins (cookies) du navigateur
  • Essayez dans une fenêtre de navigation privée/incognito
Si npm run dev échoue :
  • Exécutez npm run check pour voir les erreurs TypeScript
  • Vérifiez que tous les fichiers ont été créés correctement
  • Vérifiez que toutes les dépendances sont installées : npm install
Toujours bloqué ? Consultez la communauté Auth0 ou le Discord SvelteKit pour obtenir de l’aide.