> For the complete documentation index, see [llms.txt](https://gitbook.com/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gitbook.com/docs/documentation/zh/publish/adaptive-content/enabling-adaptive-content/cookies.md). Agents can also search and read this documentation through its [MCP server](https://gitbook.com/docs/~gitbook/mcp).

# Cookie

通过公共或签名 Cookie 将访客数据传入你的文档

{% hint style="info" %}
前往我们的指南，查看 [完整操作指南](https://gitbook.com/docs/guides/docs-personalization-and-authentication/setting-up-adaptive-content.md) 了解如何使用 Cookie 设置自适应内容。
{% endhint %}

{% hint style="warning" %}
使用 cookie 自适应内容需要向你的应用添加代码。

只有当你的网站通过 [自定义域名](https://gitbook.com/docs/documentation/zh/publish/custom-domain.md).
{% 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/documentation/zh/publish/adaptive-content/enabling-adaptive-content.md#set-an-unsigned-claim) 对象进行定义。
{% endhint %}

### 已签名 cookie

若要更安全地向 GitBook 传递数据，你需要在应用中将数据作为 [JSON Web Token](https://jwt.io/introduction) 放入名为 `gitbook-visitor-token` 的 Cookie 中，并将其绑定到你的域名。

要进行此设置，你需要调整应用的登录流程，加入以下步骤：

{% stepper %}
{% step %}
**用户登录到你的应用时生成一个 JWT**

每当用户登录到你的产品时，生成一个包含已认证用户信息中所选属性的 JWT。
{% endstep %}

{% step %}
**使用网站的访客签名密钥对 JWT 进行签名**

然后，确保使用网站的 **访客签名密钥**对 JWT 进行签名。启用自适应内容后，你可以在网站的受众设置中找到此密钥。
{% endstep %}

{% step %}
**将 JWT 存储在通配符会话 cookie 中**

最后，你需要将包含用户信息的已签名 JWT 存储到通配符会话 Cookie 中 **并将其设置在你的产品域名下**.

例如，如果你的应用通过 `app.acme.org` 域名提供服务，则需要在 `.acme.org` 通配符域名下创建 Cookie。
{% 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('/'); // 示例重定向
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://gitbook.com/docs/documentation/zh/publish/adaptive-content/enabling-adaptive-content/cookies.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
