Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import SignInFlowSummary from '../../fragments/_web-sign-in-flow-summary.mdx';

import ServerActionsTip from './_server-actions-tip.mdx';

### Konfigurationen vorbereiten \{#prepare-configs}
### Konfiguration vorbereiten \{#prepare-configs}

Bereite die Konfiguration für den Logto-Client vor:

Expand All @@ -15,15 +15,15 @@ import { LogtoNextConfig } from '@logto/next';
export const logtoConfig: LogtoNextConfig = {
appId: '<your-application-id>',
appSecret: '<your-app-secret-copied-from-console>',
endpoint: '<your-logto-endpoint>', // Z. B. http://localhost:3001
baseUrl: '<your-nextjs-app-base-url>', // Z. B. http://localhost:3000
endpoint: '<your-logto-endpoint>', // Z.B. http://localhost:3001
baseUrl: '<your-nextjs-app-base-url>', // Z.B. http://localhost:3000
cookieSecret: 'complex_password_at_least_32_characters_long',
cookieSecure: process.env.NODE_ENV === 'production',
};
```

**Hinweis:**
Wenn du eine Umgebungsvariable für `cookieSecret` verwendest (z. B. `process.env.LOGTO_COOKIE_SECRET`), stelle sicher, dass der Wert mindestens 32 Zeichen lang ist. Wenn diese Anforderung nicht erfüllt ist, wirft Logto während des Builds oder zur Laufzeit folgenden Fehler:
Wenn du eine Umgebungsvariable für `cookieSecret` verwendest (z. B. `process.env.LOGTO_COOKIE_SECRET`), stelle sicher, dass der Wert mindestens 32 Zeichen lang ist. Wenn diese Anforderung nicht erfüllt ist, wirft Logto während des Build- oder Laufzeitprozesses folgenden Fehler:

`TypeError: Either sessionWrapper or encryptionKey must be provided for CookieStorage`

Expand All @@ -39,9 +39,9 @@ Um diesen Fehler zu vermeiden, stelle sicher, dass die Umgebungsvariable korrekt

### Callback behandeln \{#handle-callback}

Nachdem sich der Benutzer angemeldet hat, leitet Logto den Benutzer zurück zur oben konfigurierten Redirect-URI. Es gibt jedoch noch Dinge zu tun, damit deine Anwendung richtig funktioniert.
Nachdem sich der Benutzer angemeldet hat, leitet Logto den Benutzer zurück zur oben konfigurierten Redirect-URI. Es gibt jedoch noch weitere Schritte, damit deine Anwendung korrekt funktioniert.

Wir stellen eine Hilfsfunktion `handleSignIn` bereit, um den Sign-In-Callback zu behandeln:
Wir stellen eine Hilfsfunktion `handleSignIn` bereit, um den Sign-In-Callback zu verarbeiten:

```tsx title="app/callback/route.ts"
import { handleSignIn } from '@logto/next/server-actions';
Expand All @@ -61,7 +61,7 @@ export async function GET(request: NextRequest) {

#### Sign-In- und Sign-Out-Button implementieren \{#implement-sign-in-and-sign-out-button}

Im Next.js App Router werden Ereignisse in Client-Komponenten behandelt, daher müssen wir zuerst zwei Komponenten erstellen: `SignIn` und `SignOut`.
Im Next.js App Router werden Events in Client-Komponenten behandelt, daher müssen wir zuerst zwei Komponenten erstellen: `SignIn` und `SignOut`.

```tsx title="app/sign-in.tsx"
'use client';
Expand Down Expand Up @@ -107,21 +107,21 @@ const SignOut = ({ onSignOut }: Props) => {
export default SignOut;
```

Denke daran, `'use client'` am Anfang der Datei hinzuzufügen, um anzugeben, dass diese Komponenten Client-Komponenten sind.
Denke daran, `'use client'` am Anfang der Datei hinzuzufügen, um anzugeben, dass es sich um Client-Komponenten handelt.

#### Buttons zur Startseite hinzufügen \{#add-buttons-to-home-page}

<ServerActionsTip />

Fügen wir nun die Sign-In- und Sign-Out-Buttons auf deiner Startseite hinzu. Wir müssen die Serveraktionen im SDK bei Bedarf aufrufen. Um dabei zu helfen, verwende `getLogtoContext`, um den Authentifizierungsstatus abzurufen.
Jetzt fügen wir die Sign-In- und Sign-Out-Buttons auf deiner Startseite hinzu. Wir müssen die Serveraktionen im SDK bei Bedarf aufrufen. Um dabei zu helfen, verwende `getLogtoContext`, um den Authentifizierungsstatus abzurufen.

```tsx title="app/page.tsx"
import { getLogtoContext, signIn, signOut } from '@logto/next/server-actions';
import SignIn from './sign-in';
import SignOut from './sign-out';
import { logtoConfig } from './logto';

const Home = () => {
export default async function Home() {
const { isAuthenticated, claims } = await getLogtoContext(logtoConfig);

return (
Expand Down Expand Up @@ -150,9 +150,7 @@ const Home = () => {
)}
</nav>
);
};

export default Home;
}
```

<Checkpoint />
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const logtoConfig: LogtoNextConfig = {
```

**Nota:**
Si utilizas una variable de entorno para `cookieSecret` (por ejemplo, `process.env.LOGTO_COOKIE_SECRET`), asegúrate de que el valor tenga al menos 32 caracteres. Si no se cumple este requisito, Logto lanzará el siguiente error durante la compilación o en tiempo de ejecución:
Si usas una variable de entorno para `cookieSecret` (por ejemplo, `process.env.LOGTO_COOKIE_SECRET`), asegúrate de que el valor tenga al menos 32 caracteres. Si no se cumple este requisito, Logto lanzará el siguiente error durante la compilación o en tiempo de ejecución:

`TypeError: Either sessionWrapper or encryptionKey must be provided for CookieStorage`

Expand All @@ -39,7 +39,7 @@ Para evitar este error, asegúrate de que la variable de entorno esté correctam

### Manejar el callback \{#handle-callback}

Después de que el usuario inicie sesión, Logto redirigirá al usuario de vuelta al URI de redirección configurado anteriormente. Sin embargo, aún hay cosas que hacer para que tu aplicación funcione correctamente.
Después de que el usuario inicie sesión, Logto redirigirá al usuario de vuelta al URI de redirección configurado anteriormente. Sin embargo, aún hay cosas por hacer para que tu aplicación funcione correctamente.

Proporcionamos una función auxiliar `handleSignIn` para manejar el callback de inicio de sesión:

Expand Down Expand Up @@ -77,7 +77,7 @@ const SignIn = ({ onSignIn }: Props) => {
onSignIn();
}}
>
Sign In
Iniciar sesión
</button>
);
};
Expand All @@ -99,7 +99,7 @@ const SignOut = ({ onSignOut }: Props) => {
onSignOut();
}}
>
Sign Out
Cerrar sesión
</button>
);
};
Expand All @@ -113,15 +113,15 @@ Recuerda agregar `'use client'` en la parte superior del archivo para indicar qu

<ServerActionsTip />

Ahora vamos a agregar los botones de inicio y cierre de sesión en tu página de inicio. Necesitamos llamar a las acciones del servidor en el SDK cuando sea necesario. Para ayudarte con esto, utiliza `getLogtoContext` para obtener el estado de autenticación.
Ahora vamos a agregar los botones de inicio y cierre de sesión en tu página de inicio. Necesitamos llamar a las acciones del servidor en el SDK cuando sea necesario. Para ayudarte con esto, usa `getLogtoContext` para obtener el estado de autenticación.

```tsx title="app/page.tsx"
import { getLogtoContext, signIn, signOut } from '@logto/next/server-actions';
import SignIn from './sign-in';
import SignOut from './sign-out';
import { logtoConfig } from './logto';

const Home = () => {
export default async function Home() {
const { isAuthenticated, claims } = await getLogtoContext(logtoConfig);

return (
Expand Down Expand Up @@ -150,9 +150,7 @@ const Home = () => {
)}
</nav>
);
};

export default Home;
}
```

<Checkpoint />
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ import SignIn from './sign-in';
import SignOut from './sign-out';
import { logtoConfig } from './logto';

const Home = () => {
export default async function Home() {
const { isAuthenticated, claims } = await getLogtoContext(logtoConfig);

return (
Expand Down Expand Up @@ -150,9 +150,7 @@ const Home = () => {
)}
</nav>
);
};

export default Home;
}
```

<Checkpoint />
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export const logtoConfig: LogtoNextConfig = {

`TypeError: Either sessionWrapper or encryptionKey must be provided for CookieStorage`

このエラーを防ぐには、環境変数が正しく設定されているか、または 32 文字以上のフォールバック値を用意してください
このエラーを防ぐには、環境変数が正しく設定されているか、または 32 文字以上のフォールバック値を指定してください

### リダイレクト URI の設定 \{#configure-redirect-uris}

Expand All @@ -39,7 +39,7 @@ export const logtoConfig: LogtoNextConfig = {

### コールバックの処理 \{#handle-callback}

ユーザーがサインインした後、Logto は上記で設定したリダイレクト URI にユーザーをリダイレクトします。ただし、アプリケーションが正しく動作するためには、まだやるべきことがあります
ユーザーがサインインした後、Logto は上記で設定したリダイレクト URI にユーザーをリダイレクトします。ただし、アプリケーションが正しく動作するためには、さらに処理が必要です

サインインコールバックを処理するためのヘルパー関数 `handleSignIn` を提供しています:

Expand Down Expand Up @@ -77,7 +77,7 @@ const SignIn = ({ onSignIn }: Props) => {
onSignIn();
}}
>
Sign In
サインイン
</button>
);
};
Expand All @@ -99,29 +99,29 @@ const SignOut = ({ onSignOut }: Props) => {
onSignOut();
}}
>
Sign Out
サインアウト
</button>
);
};

export default SignOut;
```

これらのコンポーネントがクライアントコンポーネントであることを示すため、ファイルの先頭に `'use client'` を追加することを忘れないでください
これらのコンポーネントがクライアントコンポーネントであることを示すため、ファイルの先頭に `'use client'` を追加するのを忘れないでください

#### ホームページにボタンを追加 \{#add-buttons-to-home-page}

<ServerActionsTip />

次に、ホームページにサインイン・サインアウトボタンを追加します。必要に応じて SDK のサーバーアクションを呼び出す必要があります。そのために、`getLogtoContext` を使って認証 (Authentication) 状態を取得します。
次に、ホームページにサインイン・サインアウトボタンを追加します。必要に応じて SDK のサーバーアクションを呼び出す必要があります。これを助けるために、`getLogtoContext` を使って認証 (Authentication) 状態を取得します。

```tsx title="app/page.tsx"
import { getLogtoContext, signIn, signOut } from '@logto/next/server-actions';
import SignIn from './sign-in';
import SignOut from './sign-out';
import { logtoConfig } from './logto';

const Home = () => {
export default async function Home() {
const { isAuthenticated, claims } = await getLogtoContext(logtoConfig);

return (
Expand Down Expand Up @@ -150,9 +150,7 @@ const Home = () => {
)}
</nav>
);
};

export default Home;
}
```

<Checkpoint />
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import SignInFlowSummary from '../../fragments/_web-sign-in-flow-summary.mdx';

import ServerActionsTip from './_server-actions-tip.mdx';

### 구성 준비하기 \{#prepare-configs}
### 설정 준비하기 \{#prepare-configs}

Logto 클라이언트를 위한 구성을 준비하세요:
Logto 클라이언트를 위한 설정을 준비하세요:

```ts title="app/logto.ts"
import { LogtoNextConfig } from '@logto/next';
Expand All @@ -27,7 +27,7 @@ export const logtoConfig: LogtoNextConfig = {

`TypeError: Either sessionWrapper or encryptionKey must be provided for CookieStorage`

이 오류를 방지하려면 환경 변수가 올바르게 설정되어 있거나, 최소 길이 32자의 대체 값을 제공해야 합니다.
이 오류를 방지하려면, 환경 변수가 올바르게 설정되어 있거나 최소 길이 32자의 대체 값을 제공해야 합니다.

### 리디렉션 URI 구성하기 \{#configure-redirect-uris}

Expand Down Expand Up @@ -61,7 +61,7 @@ export async function GET(request: NextRequest) {

#### 로그인 및 로그아웃 버튼 구현하기 \{#implement-sign-in-and-sign-out-button}

Next.js App Router에서는 이벤트가 클라이언트 컴포넌트에서 처리되므로, 먼저 `SignIn`과 `SignOut` 두 개의 컴포넌트를 생성해야 합니다.
Next.js App Router에서는 이벤트가 클라이언트 컴포넌트에서 처리되므로, 먼저 `SignIn`과 `SignOut` 두 개의 컴포넌트를 만들어야 합니다.

```tsx title="app/sign-in.tsx"
'use client';
Expand Down Expand Up @@ -113,15 +113,15 @@ export default SignOut;

<ServerActionsTip />

이제 홈 페이지에 로그인 및 로그아웃 버튼을 추가해 봅시다. 필요할 때 SDK의 서버 액션을 호출해야 합니다. 이를 돕기 위해 `getLogtoContext`를 사용하여 인증 (Authentication) 상태를 가져올 수 있습니다.
이제 홈 페이지에 로그인 및 로그아웃 버튼을 추가해 봅시다. 필요할 때 SDK의 서버 액션을 호출해야 합니다. 이를 돕기 위해 `getLogtoContext`를 사용하여 인증 (Authentication) 상태를 가져옵니다.

```tsx title="app/page.tsx"
import { getLogtoContext, signIn, signOut } from '@logto/next/server-actions';
import SignIn from './sign-in';
import SignOut from './sign-out';
import { logtoConfig } from './logto';

const Home = () => {
export default async function Home() {
const { isAuthenticated, claims } = await getLogtoContext(logtoConfig);

return (
Expand Down Expand Up @@ -150,9 +150,7 @@ const Home = () => {
)}
</nav>
);
};

export default Home;
}
```

<Checkpoint />
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,11 @@ Para evitar esse erro, certifique-se de que a variável de ambiente esteja corre

<WebConfigureRedirectUris />

### Lidar com o callback \{#handle-callback}
### Tratar o callback \{#handle-callback}

Após o usuário fazer login, o Logto irá redirecionar o usuário de volta para o URI de redirecionamento configurado acima. No entanto, ainda há coisas a serem feitas para que seu aplicativo funcione corretamente.
Após o usuário fazer login, o Logto irá redirecioná-lo de volta para o URI de redirecionamento configurado acima. No entanto, ainda há coisas a serem feitas para que seu aplicativo funcione corretamente.

Nós fornecemos uma função auxiliar `handleSignIn` para lidar com o callback de login:
Nós fornecemos uma função auxiliar `handleSignIn` para tratar o callback de login:

```tsx title="app/callback/route.ts"
import { handleSignIn } from '@logto/next/server-actions';
Expand All @@ -61,7 +61,7 @@ export async function GET(request: NextRequest) {

#### Implementar botão de login e logout \{#implement-sign-in-and-sign-out-button}

No Next.js App Router, os eventos são tratados em componentes de cliente, então precisamos criar dois componentes primeiro: `SignIn` e `SignOut`.
No Next.js App Router, eventos são tratados em componentes de cliente, então precisamos criar dois componentes primeiro: `SignIn` e `SignOut`.

```tsx title="app/sign-in.tsx"
'use client';
Expand Down Expand Up @@ -113,15 +113,15 @@ Lembre-se de adicionar `'use client'` no topo do arquivo para indicar que esses

<ServerActionsTip />

Agora vamos adicionar os botões de login e logout na sua página inicial. Precisamos chamar as server actions do SDK quando necessário. Para ajudar com isso, use `getLogtoContext` para buscar o status de autenticação.
Agora vamos adicionar os botões de login e logout na sua página inicial. Precisamos chamar as server actions do SDK quando necessário. Para ajudar nisso, use `getLogtoContext` para buscar o status de autenticação.

```tsx title="app/page.tsx"
import { getLogtoContext, signIn, signOut } from '@logto/next/server-actions';
import SignIn from './sign-in';
import SignOut from './sign-out';
import { logtoConfig } from './logto';

const Home = () => {
export default async function Home() {
const { isAuthenticated, claims } = await getLogtoContext(logtoConfig);

return (
Expand Down Expand Up @@ -150,9 +150,7 @@ const Home = () => {
)}
</nav>
);
};

export default Home;
}
```

<Checkpoint />
Loading
Loading