Skip to main content
This Quickstart is currently in Beta. We’d love to hear your feedback!

AI Prompt

Using AI to integrate Auth0? Add this prompt to Cursor, Windsurf, Copilot, Claude Code or your favourite AI-powered IDE to speed up development.
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:

  # 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.
Prerequisites: Before you begin, ensure you have the following installed:Svelte Version Compatibility: This quickstart works with Svelte 5.x and newer.

Get Started

This quickstart demonstrates how to add Auth0 authentication to a Svelte application. You’ll build a secure single-page app with login, logout, and user profile features using the Auth0 SPA JS SDK.
1

Create a new project

Create a new Svelte project for this Quickstart
npx sv create auth0-svelte --template minimal --types ts --no-add-ons --no-install
Open the project
cd auth0-svelte
2

Install the Auth0 SPA SDK

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

Setup your Auth0 App

Next up, you need to create a new app on your Auth0 tenant and add the environment variables to your project.You can choose to do this automatically by running a CLI command or do it manually via the Dashboard:
  • CLI
  • Dashboard
Run the following shell command on your project’s root directory to create an Auth0 app and generate a .env file:
4

Create the Auth0 store

Create the store file
mkdir -p src/lib/stores && touch src/lib/stores/auth.ts
Add the following code to manage authentication state
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);

  // Derived stores
  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);

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

      // Check authentication status
      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('Auth initialization error:', 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

Create Login, Logout and Profile Components

Create component files
mkdir -p src/lib/components && touch src/lib/components/LoginButton.svelte && touch src/lib/components/LogoutButton.svelte && touch src/lib/components/Profile.svelte
And add the following code snippets
6

Run your app

npm run dev
CheckpointYou should now have a fully functional Auth0 login page running on your localhost

Troubleshooting

If clicking the login button does nothing:
  1. Open browser DevTools (F12) and check the Console tab
  2. Verify .env file has real Auth0 credentials
  3. Check that Auth0 application has correct callback URLs configured
  4. Ensure VITE_AUTH0_DOMAIN is just the domain (e.g., tenant.auth0.com) without https://
“Callback URL mismatch”:
  • Go to Auth0 Dashboard → Applications → Your App → Settings
  • Add http://localhost:5173 to Allowed Callback URLs, Allowed Logout URLs, and Allowed Web Origins
  • Click “Save Changes”
“Invalid state”:
  • Clear browser cache and cookies
  • Try in an incognito/private window
If npm run dev fails:
  • Run npm run check to see TypeScript errors
  • Verify all files were created correctly
  • Check that all dependencies are installed: npm install
Still stuck? Check the Auth0 Community or SvelteKit Discord for help.