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

# Svelte アプリケーションにログイン機能を追加する

> このガイドでは、Auth0 SPA JS SDK を使用して、Svelte で構築されたシングルページアプリケーション（SPA）に Auth0 を統合し、認証を追加して、ユーザープロファイル情報を表示する方法を説明します。

このQuickstartは現在**Beta**版です。ぜひフィードバックをお寄せください！

> [accordion] AIプロンプト
>
> **Auth0 の統合に AI を活用していますか？** 開発をスピードアップするには、このプロンプトを Cursor、Windsurf、Copilot、Claude Code、またはお使いの AI 搭載 IDE に追加してください。
>
> ```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:
>
>   # Node.jsとnpmが利用可能か確認する
>   node --version && npm --version
>
> Then examine the current directory:
>
>   # 既存の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:
>   # Auth0 CLIがインストールされていない場合はインストールする
>   brew tap auth0/auth0-cli && brew install auth0
>
>   # Auth0アプリをセットアップして.envファイルを生成する
>   auth0 qs setup --app --type spa --framework svelte --build-tool vite --name "My App" --port 5173
>
> If Windows (PowerShell):
>   # Auth0 CLIがインストールされていない場合はインストールする
>   scoop bucket add auth0 https://github.com/auth0/scoop-auth0-cli.git
>   scoop install auth0
>
>   # Auth0アプリをセットアップして.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.
> ```

> [!NOTE]
>
> **前提条件:** 始める前に、以下がインストールされていることを確認してください。
>
> * **[Node.js](https://nodejs.org/en/download)** 20 LTS 以降
> * **[npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)** 10 以上、または **[yarn](https://classic.yarnpkg.com/lang/en/docs/install/)** 1.22 以上、または **[pnpm](https://pnpm.io/installation)** 8 以上
>
> **Svelte のバージョン互換性:** この Quickstart は **Svelte 5.x** 以降に対応しています。

## はじめに

この Quickstart では、Svelte アプリケーションに Auth0 の認証を追加する方法を説明します。Auth0 SPA JS SDK を使用して、ログイン、ログアウト、ユーザープロファイル機能を備えた安全なシングルページアプリケーションを構築します。

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

このQuickstart用の新しいSvelteプロジェクトを作成する

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

プロジェクトを開く

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

**2. Auth0 SPA SDKをインストールする**

```shellscript theme={null}
npm install && npm install @auth0/auth0-spa-js
```

**3. Auth0 Appを設定する**

次に、Auth0 テナントに新しいアプリを作成し、環境変数をプロジェクトに追加します。

Auth0 App の設定方法は 3 つあります。Quick Setup ツール (推奨) を使う方法、CLI コマンドを実行する方法、または Auth0 Dashboard で手動設定する方法です。

> [tab] クイックセットアップ（推奨）
>
> Auth0 App を作成し、正しい設定値があらかじめ入力された `.env` ファイルをコピーします。

> [tab] CLI
>
> Auth0 App を作成して `.env` ファイルを生成するには、プロジェクトのルートディレクトリで次のコマンドを実行します。
>
> ```shellscript Mac theme={null}
> # Auth0 CLI をインストールします（まだインストールしていない場合）
> brew tap auth0/auth0-cli && brew install auth0
>
> # Auth0 App を設定し、.env ファイルを生成します
> auth0 qs setup --app --type spa --framework svelte --build-tool vite --name "My App" --port 5173
> ```
>
> ```powershell Windows theme={null}
> # Auth0 CLI をインストールします（まだインストールしていない場合）
> scoop bucket add auth0 https://github.com/auth0/scoop-auth0-cli.git
> scoop install auth0
>
> # Auth0 App を設定し、.env ファイルを生成します
> auth0 qs setup --app --type spa --framework svelte --build-tool vite --name "My App" --port 5173
> ```
>
> > [!NOTE]
> >
> > このコマンドでは、次の処理が行われます。
> >
> > 1. 認証済みかどうかを確認します (必要に応じてログインを求められます)
> > 2. `http://localhost:5173` 用に設定された Auth0 Single Page Application を作成します
> > 3. `VITE_AUTH0_DOMAIN` と `VITE_AUTH0_CLIENT_ID` を含む `.env` ファイルを生成します

> [tab] Dashboard
>
> 始める前に、プロジェクトのルートディレクトリに `.env` ファイルを作成してください。
>
> ```shellscript .env theme={null}
> VITE_AUTH0_DOMAIN=YOUR_AUTH0_APP_DOMAIN
> VITE_AUTH0_CLIENT_ID=YOUR_AUTH0_APP_CLIENT_ID
> ```
>
> 1. [Auth0 Dashboard](https://manage.auth0.com/dashboard/) を開きます
> 2. **アプリケーション** > **アプリケーション** > **Create Application** をクリックします
> 3. ポップアップでアプリ名を入力し、アプリの種類として `Single Page Web Application` を選択して **Create** をクリックします
> 4. アプリケーションの Details ページで **設定** タブに切り替えます
> 5. `.env` ファイル内の `YOUR_AUTH0_APP_DOMAIN` と `YOUR_AUTH0_APP_CLIENT_ID` を、ダッシュボードの **Domain** と **Client ID** の値に置き換えます
>
> 最後に、アプリケーションの Details ページにある **設定** タブで、次の URL を設定します。
>
> **Allowed Callback URLs:**
>
> ```
> http://localhost:5173
> ```
>
> **Allowed Logout URLs:**
>
> ```
> http://localhost:5173
> ```
>
> **Allowed Web Origins:**
>
> ```
> http://localhost:5173
> ```
>
> > [!NOTE]
> >
> > **Allowed Callback URLs** は、authentication の完了後にユーザーを安全にアプリケーションへ戻すための重要なセキュリティ対策です。一致する URL が設定されていないと、ログインプロセスは失敗し、ユーザーはアプリにアクセスできず Auth0 のエラーページに移動します。
> >
> > **Allowed Logout URLs** は、サインアウト後にスムーズな user experience を提供するうえで重要です。一致する URL がないと、logout の後にユーザーはアプリケーションへリダイレクトされず、代わりに一般的な Auth0 のページに留まります。
> >
> > **Allowed Web Origins** は、サイレント認証に不可欠です。これがないと、ユーザーはページを更新したときや、後でもう一度アプリに戻ったときにログアウトされます。

**4. Auth0ストアを作成する**

ストアファイルを作成する

```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
```

認証状態を管理するため、次のコードを追加します

```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);

  // 派生ストア
  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 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. Login、Logout、プロファイルのコンポーネントを作成する**

コンポーネントファイルを作成する

```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
```

次のコードスニペットを追加します

**6. アプリを起動する**

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

> [!TIP]
>
> **確認**
>
> これで、[localhost](http://localhost:5173/) 上で Auth0 のログインページが正常に動作しているはずです

***

## トラブルシューティング

> [accordion] ログインできない
>
> ログインボタンをクリックしても何も起こらない場合:
>
> 1. ブラウザの DevTools (F12) を開き、Console タブを確認します
> 2. `.env` ファイルに有効な Auth0 の資格情報が設定されていることを確認します
> 3. Auth0 アプリケーションに正しい callback URL が設定されていることを確認します
> 4. `VITE_AUTH0_DOMAIN` には、`https://` を付けずにドメイン (例: `tenant.auth0.com`) のみを設定してください

> [accordion] 認証エラー
>
> **"Callback URL mismatch"**:
>
> * Auth0 Dashboard → アプリケーション → Your App → 設定 に移動します
> * Allowed Callback URLs、Allowed Logout URLs、Allowed Web Origins に `http://localhost:5173` を追加します
> * 「Save Changes」をクリックします
>
> **"Invalid state"**:
>
> * ブラウザのキャッシュと Cookie を削除します
> * シークレットウィンドウまたはプライベートウィンドウで試します

> [accordion] 開発サーバーの問題
>
> `npm run dev` が失敗する場合:
>
> * `npm run check` を実行して TypeScript のエラーを確認します
> * すべてのファイルが正しく作成されていることを確認します
> * 必要な依存関係がすべてインストールされていることを確認します: `npm install`

> [!TIP]
>
> まだ解決しない場合は、[Auth0 Community](https://community.auth0.com/) または [SvelteKit Discord](https://svelte.dev/chat) でサポートを確認してください。
