Cookie
使用 Bun 的原生 API 处理 HTTP Cookie
Bun 提供了两个用于处理 HTTP Cookie 的原生 API:Bun.Cookie 和 Bun.CookieMap。它们可以解析、生成和操作 HTTP 请求与响应中的 Cookie。
CookieMap 类
Bun.CookieMap 是一个类似 Map 的 cookie 集合。它实现了 Iterable,因此可以与 for...of 循环和其他迭代方法一起使用。
// 创建空的 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 的一个实例:
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。
// 通过名称获取 cookie
const cookie = cookies.get("session");
if (cookie != null) {
console.log(cookie);
}
has(name: string): boolean
检查是否存在指定名称的 cookie。
// 检查 cookie 是否存在
if (cookies.has("session")) {
// Cookie 存在
}
set(name: string, value: string, options?: CookieInit): void
set(options: CookieInit): void
set(cookie: Cookie): void
添加或更新一个 cookie。默认的 cookie 设置为 { path: "/", sameSite: "lax" }。
// 通过名称和值设置
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
delete(name: string, options: Omit<CookieStoreDeleteOptions, "name">): void
从 map 中移除 cookie。应用到 Response 时,删除操作会添加一个值为空字符串且过期日期已过的 cookie。只有当域和路径与创建该 cookie 时使用的域和路径匹配时,浏览器才会删除该 cookie。
// 用默认域和路径通过名称删除
cookies.delete("session");
// 带域和路径选项删除
cookies.delete({
name: "session",
domain: "example.com",
path: "/admin",
});
toJSON(): Record<string, string>
将 cookie map 转换为可序列化的格式。
const json = cookies.toJSON();
toSetCookieHeaders(): string[]
返回一个包含所有 cookie 变更对应的 Set-Cookie 标头值的数组。
将此方法用于 Bun.serve() 以外的 HTTP 服务器。在 Bun.serve() 中,无需调用此方法:Bun 会自动将你对 req.cookies map 所做的任何更改应用到响应标头中。
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 提供了多种迭代方法:
// 迭代 [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 的数量。
console.log(cookies.size); // cookie 数量
Cookie 类
Bun.Cookie 表示一个 HTTP cookie,包括名称、值以及属性。
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,
});
构造函数
// 基础构造函数,带名称和值
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);
属性
cookie.name; // 字符串 - Cookie 名称
cookie.value; // 字符串 - Cookie 值
cookie.domain; // 字符串 | null - 域作用域(未指定时为 null)
cookie.path; // 字符串 - URL 路径作用域(默认为 "/")
cookie.expires; // Date | undefined - 过期日期
cookie.secure; // 布尔值 - 要求使用 HTTPS
cookie.sameSite; // "strict" | "lax" | "none" - SameSite 设置
cookie.partitioned; // 布尔值 - Cookie 是否已分区(CHIPS)
cookie.maxAge; // 数字 | undefined - 最大存活时间(秒)
cookie.httpOnly; // 布尔值 - 只能通过 HTTP 访问(不能通过 JavaScript 访问)
方法
isExpired(): boolean
检查 cookie 是否已过期。当同时设置了 maxAge 和 expires 时,按照 RFC 6265 的要求,以 maxAge 为准。
// 已过期 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
// 非正数的 maxAge 会使 cookie 立即过期
const deletedCookie = new Bun.Cookie("name", "value", { maxAge: 0 });
console.log(deletedCookie.isExpired()); // true
// 会话 cookie(无过期时间)
const sessionCookie = new Bun.Cookie("name", "value");
console.log(sessionCookie.isExpired()); // false
serialize(): string
toString(): string
返回适用于 Set-Cookie 头的字符串格式。
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=Wed, 19 Mar 2025 15:03:26 GMT; Secure; HttpOnly; SameSite=Strict"
console.log(cookie.toString());
// => "session=abc123; Domain=example.com; Path=/admin; Expires=Wed, 19 Mar 2025 15:03:26 GMT; Secure; HttpOnly; SameSite=Strict"
toJSON(): CookieInit
将 cookie 转换为适合 JSON 序列化的普通对象。
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.parse(cookieString: string): Cookie
将 cookie 字符串解析为 Cookie 实例。
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.from(name: string, value: string, options?: CookieInit): Cookie
用于创建 cookie 的工厂方法。
const cookie = Bun.Cookie.from("session", "abc123", {
httpOnly: true,
secure: true,
maxAge: 3600,
});
类型定义
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 | null;
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]>;
}