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

# Cookie

> 使用 Bun 内置的 Cookie API 在 HTTP 请求和响应中处理 Cookie

Bun 有一个内置的 API 用于在 HTTP 请求和响应中处理 Cookie。`BunRequest` 对象暴露了一个 `cookies` 属性，它是一个用于读取和修改 Cookie 的 `CookieMap`。在使用 `routes` 时，`Bun.serve()` 会自动跟踪对 `request.cookies.set` 的调用，并将它们应用到响应中。

## 读取 Cookie

使用 `BunRequest` 对象上的 `cookies` 属性从传入请求中读取 Cookie：

```ts theme={null}
Bun.serve({
  routes: {
    "/profile": req => {
      // 从请求中访问 Cookie
      const userId = req.cookies.get("user_id");
      const theme = req.cookies.get("theme") || "light";

      return Response.json({
        userId,
        theme,
        message: "个人资料页",
      });
    },
  },
});
```

## 设置 Cookie

要设置 Cookie，使用 `BunRequest` 对象上的 `CookieMap` 的 `set` 方法。

```ts theme={null}
Bun.serve({
  routes: {
    "/login": req => {
      const cookies = req.cookies;

      // 通过多种选项设置 Cookie
      cookies.set("user_id", "12345", {
        maxAge: 60 * 60 * 24 * 7, // 1 周
        httpOnly: true,
        secure: true,
        path: "/",
      });

      // 添加主题偏好 Cookie
      cookies.set("theme", "dark");

      // 从请求修改的 Cookie 会自动应用到响应
      return new Response("登录成功");
    },
  },
});
```

## 删除 Cookie

要删除 Cookie，使用 `request.cookies`（`CookieMap`）对象的 `delete` 方法：

```ts theme={null}
Bun.serve({
  routes: {
    "/logout": req => {
      // 删除 user_id Cookie
      req.cookies.delete("user_id", {
        path: "/",
      });

      return new Response("已成功登出");
    },
  },
});
```

被删除的 Cookie 会在响应中变成 `Set-Cookie` 头部，其中 `Expires` 属性设置为过去的时间，`value` 为空。
