Passer au contenu principal
Ce guide de démarrage rapide est actuellement en bêta. N’hésitez pas à nous faire part de vos commentaires!

Instruction d’IA

Vous utilisez l’IA pour intégrer Auth0 ? Ajoutez ce prompt à Cursor, Windsurf, Copilot, Claude Code ou à votre IDE préféré propulsé 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.

CRITICAL BEHAVIORAL INSTRUCTIONS
1. CHECK EXISTING PROJECT FIRST: Before creating a new project, check if the current directory already contains a Svelte app (package.json with Svelte dependencies). If it does, skip project creation and work with the existing project.
2. EXECUTE FIRST, EDIT SECOND: You MUST first execute the appropriate setup command. Do not show, suggest, or create any files until the setup is complete.
3. NO PLANNING: DO NOT propose a directory structure. DO NOT show a file tree. Your first action must be to run the appropriate command.
4. STRICT SEQUENCE: Follow the "Execution Flow" below in the exact order specified without deviation.
5. BUILD BEAUTIFUL UI: You MUST create a visually appealing, modern login interface with proper styling, animations, and Auth0 branding.

EXECUTION FLOW

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

  # Vérifier si Node.js et npm sont disponibles
  node --version && npm --version

Then examine the current directory:

  # Vérifier l'existence d'un projet Svelte
  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:

Execute the Auth0 setup command for your OS:

If MacOS:
  # 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 spa --framework svelte --build-tool vite --name "My App" --port 5173

If Windows (PowerShell):
  # 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 spa --framework svelte --build-tool vite --name "My App" --port 5173

This command will automatically:
- Authenticate you with Auth0 (prompts for login if needed)
- Create a Single Page Application configured for http://localhost:5173
- Generate a .env file with VITE_AUTH0_DOMAIN and VITE_AUTH0_CLIENT_ID

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 :Compatibilité des versions de Svelte : Ce guide de démarrage rapide fonctionne avec Svelte 5.x et les versions ultérieures.

Premiers pas

Ce guide de démarrage rapide explique comment ajouter l’authentification Auth0 à une application Svelte. Vous créerez une application monopage sécurisée avec des fonctions de connexion, de déconnexion et de profil d’utilisateur à l’aide du SDK Auth0 SPA JS.
1

Créer un nouveau projet

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

Installez le SDK SPA d’Auth0

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

Configurez votre application Auth0

La prochaine étape consiste à créer une nouvelle application sur votre locataire Auth0 et à ajouter les variables d’environnement à votre projet.Vous avez trois options pour configurer votre application Auth0 : utiliser l’outil Quick Setup (recommandé), exécuter une commande CLI ou faire la configuration manuellement dans l’Auth0 Dashboard :
Créez une application Auth0 et copiez le fichier .env prérempli avec les bonnes valeurs de configuration.
4

Créer le store Auth0

Créez le fichier du store
mkdir -p src/lib/stores && touch src/lib/stores/auth.ts
Ajoutez le code suivant pour gérer l’état de l’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);

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

      // Vérifier l'état 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 : 'Authentication initialization failed');
    } 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 de connexion, de déconnexion et de profil

Créer des 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 rien ne se passe lorsque vous cliquez sur le bouton de connexion :
  1. Ouvrez les outils de développement du navigateur (F12) et vérifiez l’onglet Console
  2. Vérifiez que le fichier .env contient de vrais identifiants Auth0
  3. Vérifiez que l’application Auth0 a les bonnes URL de rappel configurées
  4. Assurez-vous que VITE_AUTH0_DOMAIN contient uniquement le domaine (par ex., tenant.auth0.com), sans https://
“Callback URL mismatch” :
  • Allez dans Auth0 Dashboard → Applications → Your App → Settings
  • Ajoutez http://localhost:5173 à Allowed Callback URLs, Allowed Logout URLs et Allowed Web Origins
  • Cliquez sur “Save Changes”
“Invalid state” :
  • Effacez le cache et les témoins du navigateur
  • Essayez dans une fenêtre de navigation privée/incognito
Si npm run dev échoue :
  • Exécutez npm run check pour afficher 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
Vous êtes toujours bloqué? Consultez la communauté Auth0 ou le Discord de SvelteKit pour obtenir de l’aide.