メインコンテンツへスキップ
このクイックスタートは現在ベータ版です。ぜひご意見・ご感想をお寄せください!

AI プロンプト

AIを使ってAuth0を統合しますか? このプロンプトをCursor、Windsurf、Copilot、Claude Code、またはお好みのAI搭載IDEに追加して、開発を高速化しましょう。
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

ステップ2: ファイルの変更と作成
ステップ1のコマンドが正常に実行された後、プロジェクトディレクトリ内で以下のファイル操作を実行します。

2.1: Auth0環境設定のセットアップ

お使いのOSに応じた環境セットアップコマンドを実行します:

MacOSの場合、以下のコマンドを実行します:
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

Windowsの場合、以下のコマンドを実行します:
$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.
前提条件: 作業を始める前に、次のツールがインストールされていることを確認してください。
  • Node.js 20 LTS 以降
  • npm 10 以上、または yarn 1.22 以上、または pnpm 8 以上
  • jq — Auth0 CLI のセットアップに必要です
Svelte のバージョン互換性: このクイックスタートは Svelte 5.x 以降に対応しています。

はじめに

このクイックスタートでは、Svelte アプリケーションに Auth0 認証を追加する方法を説明します。Auth0 SPA JS ソフトウェア開発キット (SDK) を使って、ログイン、ログアウト、ユーザー プロファイル機能を備えたセキュアなシングルページ アプリケーションを構築します。
1

新しいプロジェクトを作成

このクイックスタート用に新しい Svelte プロジェクトを作成する
npx sv create auth0-svelte --template minimal --types ts --no-add-ons --no-install
プロジェクトを開く
cd auth0-svelte
2

Auth0 SPA ソフトウェア開発キット (SDK) のインストール

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

Auth0 アプリケーションを設定する

次に、Auth0 テナント上に新しいアプリを作成し、環境変数をプロジェクトに追加する必要があります。これは、CLI コマンドを実行して自動的に設定する方法と、Dashboard から手動で設定する方法のどちらかを選択できます。
次のシェルコマンドをプロジェクトのルートディレクトリで実行して、Auth0 アプリを作成し、.env ファイルを生成します。
4

Auth0 ストアの作成

ストアファイルを作成する
mkdir -p src/lib/stores && touch src/lib/stores/auth.ts
認証状態を管理するために、次のコードを追加します
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);

  // 派生ストア
  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);

      // コールバックを処理
      if (window.location.search.includes('code=')) {
        await client.handleRedirectCallback();
        window.history.replaceState({}, document.title, window.location.pathname);
      }

      // 認証ステータスを確認
      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初期化エラー:', err);
      error.set(err instanceof Error ? err.message : '認証の初期化に失敗しました');
    } 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

Login、Logout、Profile コンポーネントを作成する

コンポーネントファイルを作成する
mkdir -p src/lib/components && touch src/lib/components/LoginButton.svelte && touch src/lib/components/LogoutButton.svelte && touch src/lib/components/Profile.svelte
次のコードスニペットを追加してください
6

アプリを実行する

npm run dev
チェックポイントここまでで、localhost 上で Auth0 のログインページが問題なく動作しているはずです。

トラブルシューティング

ログインボタンをクリックしても何も起こらない場合:
  1. ブラウザの開発者ツール(F12)を開き、「Console」タブを確認する
  2. .env ファイルに実際の Auth0 クレデンシャルが設定されていることを確認する
  3. Auth0 アプリケーションに正しいコールバックURLが設定されていることを確認する
  4. VITE_AUTH0_DOMAINhttps:// を含めず、ドメインのみ(例: tenant.auth0.com)になっていることを確認する
“Callback URL mismatch” の場合:
  • Auth0 Dashboard → Applications → 対象のアプリ → Settings に移動する
  • http://localhost:5173 を 許可されたコールバックURL、許可されたログアウトURL、および Allowed Web Origins に追加する
  • 「Save Changes」をクリックする
“Invalid state” の場合:
  • ブラウザのキャッシュとクッキーをクリアする
  • シークレットモード/プライベートウィンドウで試す
npm run dev が失敗する場合:
  • npm run check を実行して TypeScript のエラーを確認する
  • すべてのファイルが正しく作成されていることを確認する
  • すべての依存関係がインストールされていることを確認する: npm install
まだ解決しない場合は、Auth0 CommunitySvelteKit Discord を参照してサポートを受けてください。