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

# Add Login to Your Svelte Application

> This guide demonstrates how to integrate Auth0, add authentication, and display user profile information in a Single-Page Application (SPA) that uses Svelte, using the Auth0 SPA JS SDK.

This Quickstart is currently in **Beta**. We'd love to hear your feedback!

> [accordion] 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.
>
> ```markdown expandable theme={null}
> 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:
>
> Execute the Auth0 setup command for your OS:
>
> If MacOS:
>   # Install Auth0 CLI if not already installed
>   brew tap auth0/auth0-cli && brew install auth0
>
>   # Set up Auth0 app and generate .env file
>   auth0 qs setup --app --type spa --framework svelte --build-tool vite --name "My App" --port 5173
>
> If Windows (PowerShell):
>   # Install Auth0 CLI if not already installed
>   scoop bucket add auth0 https://github.com/auth0/scoop-auth0-cli.git
>   scoop install auth0
>
>   # Set up Auth0 app and generate .env file
>   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.
> ```

> [!NOTE]
>
> **Prerequisites:** Before you begin, ensure you have the following installed:
>
> * **[Node.js](https://nodejs.org/en/download)** 20 LTS or newer
> * **[npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)** 10+ or **[yarn](https://classic.yarnpkg.com/lang/en/docs/install/)** 1.22+ or **[pnpm](https://pnpm.io/installation)** 8+
>
> **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

```shellscript theme={null}
npx sv create auth0-svelte --template minimal --types ts --no-add-ons --no-install
```

Open the project

```shellscript theme={null}
cd auth0-svelte
```

**2. Install the Auth0 SPA SDK**

```shellscript theme={null}
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 have three options to set up your Auth0 app: use the Quick Setup tool (recommended), run a CLI command, or configure manually via the Dashboard:

> [tab] Quick Setup (recommended)
>
> Create an Auth0 App and copy the pre-filled `.env` file with the right configuration values.

> [tab] CLI
>
> Run the following command in your project's root directory to create an Auth0 app and generate a `.env` file:
>
> ```shellscript Mac theme={null}
> # Install Auth0 CLI (if not already installed)
> brew tap auth0/auth0-cli && brew install auth0
>
> # Set up Auth0 app and generate .env file
> auth0 qs setup --app --type spa --framework svelte --build-tool vite --name "My App" --port 5173
> ```
>
> ```powershell Windows theme={null}
> # Install Auth0 CLI (if not already installed)
> scoop bucket add auth0 https://github.com/auth0/scoop-auth0-cli.git
> scoop install auth0
>
> # Set up Auth0 app and generate .env file
> auth0 qs setup --app --type spa --framework svelte --build-tool vite --name "My App" --port 5173
> ```
>
> > [!NOTE]
> >
> > This command will:
> >
> > 1. Check if you're authenticated (and prompt for login if needed)
> > 2. Create an Auth0 Single Page Application configured for `http://localhost:5173`
> > 3. Generate a `.env` file with `VITE_AUTH0_DOMAIN` and `VITE_AUTH0_CLIENT_ID`

> [tab] Dashboard
>
> Before you start, create a `.env` file on your project's root directory
>
> ```shellscript .env theme={null}
> VITE_AUTH0_DOMAIN=YOUR_AUTH0_APP_DOMAIN
> VITE_AUTH0_CLIENT_ID=YOUR_AUTH0_APP_CLIENT_ID
> ```
>
> 1. Head to the [Auth0 Dashboard](https://manage.auth0.com/dashboard/)
> 2. Click on **Applications** > **Applications** > **Create Application**
> 3. In the popup, enter a name for your app, select `Single Page Web Application` as the app type and click **Create**
> 4. Switch to the **Settings** tab on the Application Details page
> 5. Replace `YOUR_AUTH0_APP_DOMAIN` and `YOUR_AUTH0_APP_CLIENT_ID` on the `.env` file with the **Domain** and **Client ID** values from the dashboard
>
> Finally, on the **Settings** tab of your Application Details page, configure the following URLs:
>
> **Allowed Callback URLs:**
>
> ```
> http://localhost:5173
> ```
>
> **Allowed Logout URLs:**
>
> ```
> http://localhost:5173
> ```
>
> **Allowed Web Origins:**
>
> ```
> http://localhost:5173
> ```
>
> > [!NOTE]
> >
> > **Allowed Callback URLs** are a critical security measure to ensure users are safely returned to your application after authentication. Without a matching URL, the login process will fail, and users will be blocked by an Auth0 error page instead of accessing your app.
> >
> > **Allowed Logout URLs** are essential for providing a seamless user experience upon signing out. Without a matching URL, users will not be redirected back to your application after logout and will instead be left on a generic Auth0 page.
> >
> > **Allowed Web Origins** is critical for silent authentication. Without it, users will be logged out when they refresh the page or return to your app later.

**4. Create the Auth0 store**

Create the store file

```shellscript Mac/Linux theme={null}
mkdir -p src/lib/stores && touch src/lib/stores/auth.ts
```

```powershell Windows theme={null}
New-Item -ItemType Directory -Force -Path src/lib/stores
New-Item -ItemType File -Path src/lib/stores/auth.ts
```

Add the following code to manage authentication state

```typescript src/lib/stores/auth.ts lines expandable theme={null}
  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

```shellscript Mac/Linux theme={null}
mkdir -p src/lib/components && touch src/lib/components/LoginButton.svelte && touch src/lib/components/LogoutButton.svelte && touch src/lib/components/Profile.svelte
```

```powershell Windows theme={null}
New-Item -ItemType Directory -Force -Path src/lib/components
New-Item -ItemType File -Path src/lib/components/LoginButton.svelte
New-Item -ItemType File -Path src/lib/components/LogoutButton.svelte
New-Item -ItemType File -Path src/lib/components/Profile.svelte
```

And add the following code snippets

**6. Run your app**

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

> [!TIP]
>
> **Checkpoint**
>
> You should now have a fully functional Auth0 login page running on your [localhost](http://localhost:5173/)

***

## Troubleshooting

> [accordion] Login Not Working
>
> 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://`

> [accordion] Authentication Errors
>
> **"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

> [accordion] Dev Server Issues
>
> 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`

> [!TIP]
>
> Still stuck? Check the [Auth0 Community](https://community.auth0.com/) or [SvelteKit Discord](https://svelte.dev/chat) for help.
