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

Use AI to integrate Auth0

If you use an AI coding assistant like Claude Code, Cursor, or GitHub Copilot, you can add Auth0 authentication automatically in minutes using agent skills.Install:
npx skills add auth0/agent-skills
Then ask your AI assistant:
Add Auth0 authentication to my Svelte app
Your AI assistant will automatically create your Auth0 application, fetch credentials, install @auth0/auth0-spa-js, create authentication components with Svelte stores, and set up your configuration. Full agent skills documentation →
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 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:
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.