Skip to main content
Bun 通过 Bun.CookieBun.CookieMap 提供了处理 HTTP Cookie 的原生 API。这些 API 提供了快速且易于使用的方法,用于解析、生成和操作 HTTP 请求和响应中的 cookie。

CookieMap 类

Bun.CookieMap 提供了类似 Map 的接口,用于操作一组 cookies。它实现了 Iterable 接口,允许你使用 for...of 循环以及其它迭代方法。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79cookies.ts
// 创建空的 CookieMap
const cookies = new Bun.CookieMap();

// 从 cookie 字符串创建
const cookies1 = new Bun.CookieMap("name=value; foo=bar");

// 从对象创建
const cookies2 = new Bun.CookieMap({
  session: "abc123",
  theme: "dark",
});

// 从名称/值对数组创建
const cookies3 = new Bun.CookieMap([
  ["session", "abc123"],
  ["theme", "dark"],
]);

在 HTTP 服务器中使用

在 Bun 的 HTTP 服务器中,请求对象(在 routes 中)的 cookies 属性是 CookieMap 的一个实例:
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79server.ts
const server = Bun.serve({
  routes: {
    "/": req => {
      // 访问请求中的 cookies
      const cookies = req.cookies;

      // 获取指定名称的 cookie
      const sessionCookie = cookies.get("session");
      if (sessionCookie != null) {
        console.log(sessionCookie);
      }

      // 检查是否存在某个 cookie
      if (cookies.has("theme")) {
        // ...
      }

      // 设置一个 cookie,这个操作会自动应用到响应中
      cookies.set("visited", "true");

      return new Response("Hello");
    },
  },
});

console.log("服务器监听地址: " + server.url);

方法

get(name: string): string | null

根据名称获取 cookie。如果不存在则返回 null
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79get-cookie.ts
// 通过名称获取 cookie
const cookie = cookies.get("session");

if (cookie != null) {
  console.log(cookie);
}

has(name: string): boolean

检查是否存在指定名称的 cookie。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79has-cookie.ts
// 检查 cookie 是否存在
if (cookies.has("session")) {
  // Cookie 存在
}

set(name: string, value: string): void

set(options: CookieInit): void

添加或更新一个 cookie。默认的 cookie 设置为 { path: "/", sameSite: "lax" }
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79set-cookie.ts
// 通过名称和值设置
cookies.set("session", "abc123");

// 使用配置对象设置
cookies.set({
  name: "theme",
  value: "dark",
  maxAge: 3600,
  secure: true,
});

// 使用 Cookie 实例设置
const cookie = new Bun.Cookie("visited", "true");
cookies.set(cookie);

delete(name: string): void

delete(options: CookieStoreDeleteOptions): void

从 Map 中删除一个 cookie。应用于 Response 时,会添加一个值为空字符串且过期时间为过去的 cookie。只有当域和路径与原 cookie 创建时相同,浏览器才会成功删除该 cookie。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79delete-cookie.ts
// 用默认域和路径通过名称删除
cookies.delete("session");

// 带域和路径选项删除
cookies.delete({
  name: "session",
  domain: "example.com",
  path: "/admin",
});

toJSON(): Record<string, string>

将 cookie map 转换为可序列化的格式。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79cookie-to-json.ts
const json = cookies.toJSON();

toSetCookieHeaders(): string[]

返回可用于设置所有 cookie 变更的 Set-Cookie 头部字符串数组。 使用 Bun.serve() 时,不必显式调用此方法。对 req.cookies map 的任何修改都会自动应用到响应头。这一方法主要适用于其他 HTTP 服务器实现。
node-server.js
import { createServer } from "node:http";
import { CookieMap } from "bun";

const server = createServer((req, res) => {
  const cookieHeader = req.headers.cookie || "";
  const cookies = new CookieMap(cookieHeader);

  cookies.set("view-count", Number(cookies.get("view-count") || "0") + 1);
  cookies.delete("session");

  res.writeHead(200, {
    "Content-Type": "text/plain",
    "Set-Cookie": cookies.toSetCookieHeaders(),
  });
  res.end(`Found ${cookies.size} cookies`);
});

server.listen(3000, () => {
  console.log("服务器运行在 http://localhost:3000/");
});

迭代

CookieMap 提供了多种迭代方法:
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79iterate-cookies.ts
// 迭代 [name, cookie] 条目
for (const [name, value] of cookies) {
  console.log(`${name}: ${value}`);
}

// 使用 entries()
for (const [name, value] of cookies.entries()) {
  console.log(`${name}: ${value}`);
}

// 使用 keys()
for (const name of cookies.keys()) {
  console.log(name);
}

// 使用 values()
for (const value of cookies.values()) {
  console.log(value);
}

// 使用 forEach
cookies.forEach((value, name) => {
  console.log(`${name}: ${value}`);
});

属性

size: number

返回 map 中 cookie 的数量。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79cookie-size.ts
console.log(cookies.size); // cookie 数量
Bun.Cookie 表示一个 HTTP cookie,包括名称、值以及属性。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79cookie-class.ts
import { Cookie } from "bun";

// 创建基础 cookie
const cookie = new Bun.Cookie("name", "value");

// 创建带选项的 cookie
const secureSessionCookie = new Bun.Cookie("session", "abc123", {
  domain: "example.com",
  path: "/admin",
  expires: new Date(Date.now() + 86400000), // 1 天后过期
  httpOnly: true,
  secure: true,
  sameSite: "strict",
});

// 从 cookie 字符串解析
const parsedCookie = new Bun.Cookie("name=value; Path=/; HttpOnly");

// 从配置对象创建
const objCookie = new Bun.Cookie({
  name: "theme",
  value: "dark",
  maxAge: 3600,
  secure: true,
});

构造函数

https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79constructors.ts
// 基础构造函数,带名称和值
new Bun.Cookie(name: string, value: string);

// 带名称、值和选项的构造函数
new Bun.Cookie(name: string, value: string, options: CookieInit);

// 从 cookie 字符串构造
new Bun.Cookie(cookieString: string);

// 从 cookie 对象构造
new Bun.Cookie(options: CookieInit);

属性

https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79cookie-properties.ts
cookie.name; // string - Cookie 名称
cookie.value; // string - Cookie 值
cookie.domain; // string | null - 域范围(未指定为 null)
cookie.path; // string - URL 路径范围(默认 "/")
cookie.expires; // number | undefined - 过期时间戳(自 Epoch 以来的毫秒)
cookie.secure; // boolean - 是否要求 HTTPS
cookie.sameSite; // "strict" | "lax" | "none" - SameSite 设置
cookie.partitioned; // boolean - 是否隔离(CHIPS)
cookie.maxAge; // number | undefined - 最大存活秒数
cookie.httpOnly; // boolean - 仅 HTTP 可访问(不可用 JavaScript 访问)

方法

isExpired(): boolean

检查 cookie 是否已过期。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79is-expired.ts
// 已过期 cookie(日期为过去)
const expiredCookie = new Bun.Cookie("name", "value", {
  expires: new Date(Date.now() - 1000),
});
console.log(expiredCookie.isExpired()); // true

// 有效 cookie(使用 maxAge 而非 expires)
const validCookie = new Bun.Cookie("name", "value", {
  maxAge: 3600, // 1 小时(秒)
});
console.log(validCookie.isExpired()); // false

// 会话 cookie(无过期时间)
const sessionCookie = new Bun.Cookie("name", "value");
console.log(sessionCookie.isExpired()); // false

serialize(): string

toString(): string

返回适用于 Set-Cookie 头的字符串格式。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79serialize-cookie.ts
const cookie = new Bun.Cookie("session", "abc123", {
  domain: "example.com",
  path: "/admin",
  expires: new Date(Date.now() + 86400000),
  secure: true,
  httpOnly: true,
  sameSite: "strict",
});

console.log(cookie.serialize());
// => "session=abc123; Domain=example.com; Path=/admin; Expires=Sun, 19 Mar 2025 15:03:26 GMT; Secure; HttpOnly; SameSite=strict"
console.log(cookie.toString());
// => "session=abc123; Domain=example.com; Path=/admin; Expires=Sun, 19 Mar 2025 15:03:26 GMT; Secure; HttpOnly; SameSite=strict"

toJSON(): CookieInit

将 cookie 转换为适合 JSON 序列化的普通对象。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79cookie-json.ts
const cookie = new Bun.Cookie("session", "abc123", {
  secure: true,
  httpOnly: true,
});

const json = cookie.toJSON();
// => {
//   name: "session",
//   value: "abc123",
//   path: "/",
//   secure: true,
//   httpOnly: true,
//   sameSite: "lax",
//   partitioned: false
// }

// 可直接用于 JSON.stringify
const jsonString = JSON.stringify(cookie);

静态方法

解析 cookie 字符串成 Cookie 实例。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79parse-cookie.ts
const cookie = Bun.Cookie.parse("name=value; Path=/; Secure; SameSite=Lax");

console.log(cookie.name); // "name"
console.log(cookie.value); // "value"
console.log(cookie.path); // "/"
console.log(cookie.secure); // true
console.log(cookie.sameSite); // "lax"
工厂方法用于创建 cookie。
https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79cookie-from.ts
const cookie = Bun.Cookie.from("session", "abc123", {
  httpOnly: true,
  secure: true,
  maxAge: 3600,
});

类型定义

https://mintcdn.com/ikxin/RzFFGbzo0-4huILA/icons/typescript.svg?fit=max&auto=format&n=RzFFGbzo0-4huILA&q=85&s=a3dffd2241f05776d3bd25171d0c5a79types.ts
interface CookieInit {
  name?: string;
  value?: string;
  domain?: string;
  /** 默认为 '/'。若想让浏览器自行设置路径,使用空字符串。 */
  path?: string;
  expires?: number | Date | string;
  secure?: boolean;
  /** 默认为 `lax`。 */
  sameSite?: CookieSameSite;
  httpOnly?: boolean;
  partitioned?: boolean;
  maxAge?: number;
}

interface CookieStoreDeleteOptions {
  name: string;
  domain?: string | null;
  path?: string;
}

interface CookieStoreGetOptions {
  name?: string;
  url?: string;
}

type CookieSameSite = "strict" | "lax" | "none";

class Cookie {
  constructor(name: string, value: string, options?: CookieInit);
  constructor(cookieString: string);
  constructor(cookieObject?: CookieInit);

  readonly name: string;
  value: string;
  domain?: string;
  path: string;
  expires?: Date;
  secure: boolean;
  sameSite: CookieSameSite;
  partitioned: boolean;
  maxAge?: number;
  httpOnly: boolean;

  isExpired(): boolean;

  serialize(): string;
  toString(): string;
  toJSON(): CookieInit;

  static parse(cookieString: string): Cookie;
  static from(name: string, value: string, options?: CookieInit): Cookie;
}

class CookieMap implements Iterable<[string, string]> {
  constructor(init?: string[][] | Record<string, string> | string);

  get(name: string): string | null;

  toSetCookieHeaders(): string[];

  has(name: string): boolean;
  set(name: string, value: string, options?: CookieInit): void;
  set(options: CookieInit): void;
  delete(name: string): void;
  delete(options: CookieStoreDeleteOptions): void;
  delete(name: string, options: Omit<CookieStoreDeleteOptions, "name">): void;
  toJSON(): Record<string, string>;

  readonly size: number;

  entries(): IterableIterator<[string, string]>;
  keys(): IterableIterator<string>;
  values(): IterableIterator<string>;
  forEach(callback: (value: string, key: string, map: CookieMap) => void): void;
  [Symbol.iterator](): IterableIterator<[string, string]>;
}