# Cookie

{% hint style="info" %}
ガイドへ進んで [完全な手順ガイド](https://app.gitbook.com/s/LBGJKQic7BQYBXmVSjy0/docs-personalization-and-authentication/setting-up-adaptive-content) で、Cookie を使ったアダプティブコンテンツの設定方法をご確認ください。
{% endhint %}

{% hint style="warning" %}
機能フラグとともにアダプティブコンテンツを使用するには、アプリケーションにコードを追加する必要があります。

この方法は、サイトが次の配下で配信されている場合にのみ機能します。 [カスタムドメイン](https://gitbook-v2-q67etdj25-gitbook.vercel.app/url/gitbook.com/docs/documentation/ja-gitbook-documentation/publishing-documentation/custom-domain).
{% endhint %}

訪問者のブラウザ Cookie を通じて、訪問者データをドキュメントに渡すことができます。以下は、各方法の概要です。

<table data-full-width="false"><thead><tr><th width="335.125">方法</th><th width="266.6015625">ユースケース</th><th width="206.58984375">設定のしやすさ</th><th width="202">セキュリティ</th><th>形式</th></tr></thead><tbody><tr><td>署名付き Cookie <code>gitbook-visitor-token</code></td><td>API のテスト認証情報、顧客識別</td><td>署名とカスタムドメインが必要</td><td><span data-gb-custom-inline data-tag="emoji" data-code="2705">✅</span> プロパティはバックエンドによってのみ定義できます</td><td>JWT</td></tr><tr><td>公開 Cookie <code>gitbook-visitor-public</code></td><td>機能フラグ、ロール</td><td>設定が簡単</td><td><span data-gb-custom-inline data-tag="emoji" data-code="274c">❌</span> 訪問者がプロパティを上書きできます</td><td>JSON</td></tr></tbody></table>

### 公開 Cookie

公開 Cookie から GitBook にデータを渡すには、公開 `gitbook-visitor-public` Cookie を設定して、アプリケーションからデータを送信する必要があります。

以下は簡単な JavaScript の例です:

```javascript
import Cookies from 'js-cookie';

const cookieData = {
  isLoggedIn: true,
  isBetaUser: false,
};

Cookies.set('gitbook-visitor-public', JSON.stringify(cookieData), {
  secure: true,
  domain: '*.acme.org',
})
```

{% hint style="warning" %}
公開 Cookie を通じて渡されるデータは、訪問者スキーマ内で次を通して定義する必要があります。 [署名なし](https://gitbook.com/docs/publishing-documentation/adaptive-content/enabling-adaptive-content#setting-unsigned-claims) オブジェクト。
{% endhint %}

### 署名付き Cookie

GitBook により安全にデータを渡すには、データを [JSON Web Token](https://jwt.io/introduction) として、アプリケーションから次の名前の Cookie で送信する必要があります。 `gitbook-visitor-token` をドメインに関連付けます。

これを設定するには、アプリケーションのログインフローを次の手順に合わせて調整する必要があります:

{% stepper %}
{% step %}
**ユーザーがアプリケーションにログインしたときに JWT を生成する**

ユーザーが製品にログインするたびに、認証済みユーザー情報の選択した属性を含む JWT を生成します。
{% endstep %}

{% step %}
**サイトの訪問者署名鍵を使用して JWT に署名する**

次に、必ずサイトの **訪問者署名鍵**で JWT に署名してください。これは、アダプティブコンテンツを有効にした後にサイトのオーディエンス設定で確認できます。
{% endstep %}

{% step %}
**JWT をワイルドカードセッション Cookie に保存する**

最後に、ユーザー情報を含む署名済み JWT をワイルドカードセッション Cookie に保存する必要があります **を製品ドメインの下に**.

たとえば、アプリケーションが次の配下で配信されている場合 `app.acme.org` ドメインであれば、Cookie は次の配下で作成する必要があります `.acme.org` ワイルドカードドメイン。
{% endstep %}
{% endstepper %}

以下は簡単な TypeScript の例です:

```typescript
import * as jose from 'jose';

import { Request, Response } from 'express';

import { getUserInfo } from '../services/user-info-service';
import { getFeatureFlags } from '../services/feature-flags-service';

const GITBOOK_VISITOR_SIGNING_KEY = process.env.GITBOOK_VISITOR_SIGNING_KEY;
const GITBOOK_VISITOR_COOKIE_NAME = 'gitbook-visitor-token';


export async function handleAppLoginRequest(req: Request, res: Response) {
   // ログインリクエストを処理するためのビジネスロジック
   // たとえば、認証情報を確認してユーザーを認証する
   //
   // 例:
   // const loggedInUser = await authenticateUser(req.body.username, req.body.password);

   // ユーザー認証後、GitBook に渡したいユーザー情報を取得します
   // データベースまたはユーザーサービスから。
   const userInfo = await getUserInfo(loggedInUser.id);
      
   // ユーザー情報を使って JWT のペイロードを構築します
   const gitbookVisitorClaims = {
       firstName: userInfo.firstName,
       lastName: userInfo.lastName,
       isBetaUser: userInfo.isBetaUser
       products: userInfo.products.map((product) => product.name),
       featureFlags: await getFeatureFlags({userId: loggedInUser.id})
   }
   
   // クレームを使用して署名付き JWT を生成します
   const gitbookVisitorJWT = await new jose.SignJWT(gitbookVisitorClaims)
     .setProtectedHeader({ alg: 'HS256' })
     .setIssuedAt()
     .setExpirationTime('2h') // 任意の 2 時間の有効期限
     .sign(GITBOOK_VISITOR_SIGNING_KEY);
     
  // エンコードされた JWT を含む `gitbook-visitor-token` Cookie を
  // ログインハンドラーのレスポンスに含めます
  res.cookie(GITBOOK_VISITOR_COOKIE_NAME, gitbookVisitorJWT, {
     httpOnly: true,
     secure: process.env.NODE_ENV === 'production',
     maxAge: 2 * 60 * 60 * 1000, // 任意の 2 時間の有効期限
     domain: '.acme.org' //
  });
  
  // ユーザーをアプリへリダイレクトする処理を含む、ログインハンドラーの残りのロジック
  res.redirect('/'); // リダイレクトの例
}
```
