Bun は Bun.Cookie と Bun.CookieMap を通じて HTTP cookie の操作のためのネイティブ API を提供します。これらの API は、HTTP リクエストとレスポンスにおける cookie の解析、生成、操作のための高速で使いやすいメソッドを提供します。
CookieMap クラス
Bun.CookieMap は cookie のコレクションを操作するための Map ライクなインターフェースを提供します。Iterable インターフェースを実装しており、for...of ループや他の反復メソッドで使用できます。
// 空の cookie マップ
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"],
]);2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
HTTP サーバー内
Bun の HTTP サーバーでは、リクエストオブジェクトの cookies プロパティ(routes 内)は CookieMap のインスタンスです。
const server = Bun.serve({
routes: {
"/": req => {
// リクエスト cookie にアクセス
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 listening at: " + server.url);2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
メソッド
get(name: string): string | null
名前で cookie を取得します。cookie が存在しない場合は null を返します。
// 名前で取得
const cookie = cookies.get("session");
if (cookie != null) {
console.log(cookie);
}2
3
4
5
6
has(name: string): boolean
指定された名前の cookie が存在するか確認します。
// cookie が存在するか確認
if (cookies.has("session")) {
// cookie が存在します
}2
3
4
set(name: string, value: string): 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);2
3
4
5
6
7
8
9
10
11
12
13
14
delete(name: string): void
delete(options: CookieStoreDeleteOptions): void
マップから cookie を削除します。Response に適用されると、空の文字列値と過去の有効期限日付を持つ cookie が追加されます。cookie は、作成時と同じドメインとパスの場合にのみ、ブラウザで正常に削除されます。
// デフォルトのドメインとパスを使用して名前で削除
cookies.delete("session");
// ドメイン/パスオプションを使用して削除
cookies.delete({
name: "session",
domain: "example.com",
path: "/admin",
});2
3
4
5
6
7
8
9
toJSON(): Record<string, string>
cookie マップをシリアライズ可能な形式に変換します。
const json = cookies.toJSON();toSetCookieHeaders(): string[]
すべての cookie 変更を適用するために使用できる Set-Cookie ヘッダーの値の配列を返します。
Bun.serve() を使用する場合、このメソッドを明示的に呼び出す必要はありません。req.cookies マップに加えられた変更は自動的にレスポンスヘッダーに適用されます。このメソッドは主に他の HTTP サーバー実装を扱う場合に役立ちます。
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("Server running at http://localhost:3000/");
});2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
反復処理
CookieMap は反復処理のためのいくつかのメソッドを提供します。
// [名前,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}`);
});2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
プロパティ
size: number
マップ内の 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,
});2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
コンストラクター
// 名前/値の基本的なコンストラクター
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);2
3
4
5
6
7
8
9
10
11
プロパティ
cookie.name; // string - cookie 名
cookie.value; // string - cookie 値
cookie.domain; // string | null - ドメインスコープ(指定されていない場合は null)
cookie.path; // string - URL パススコープ(デフォルトは "/")
cookie.expires; // number | undefined - 有効期限タイムスタンプ(エポックからのミリ秒)
cookie.secure; // boolean - HTTPS を必要とする
cookie.sameSite; // "strict" | "lax" | "none" - SameSite 設定
cookie.partitioned; // boolean - cookie がパーティション化されているか(CHIPS)
cookie.maxAge; // number | undefined - 秒単位の最大有効期間
cookie.httpOnly; // boolean - HTTP のみでアクセス可能(JavaScript からはアクセス不可)2
3
4
5
6
7
8
9
10
メソッド
isExpired(): boolean
cookie が有効期限切れになっているか確認します。
// 有効期限切れの cookie(過去の日付)
const expiredCookie = new Bun.Cookie("name", "value", {
expires: new Date(Date.now() - 1000),
});
console.log(expiredCookie.isExpired()); // true
// 有効な cookie(expires の代わりに maxAge を使用)
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()); // false2
3
4
5
6
7
8
9
10
11
12
13
14
15
serialize(): string
toString(): string
Set-Cookie ヘッダーに適した 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=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"2
3
4
5
6
7
8
9
10
11
12
13
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);2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
静的メソッド
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"2
3
4
5
6
7
Cookie.from(name: string, value: string, options?: CookieInit): Cookie
cookie を作成するためのファクトリメソッド。
const cookie = Bun.Cookie.from("session", "abc123", {
httpOnly: true,
secure: true,
maxAge: 3600,
});2
3
4
5
型
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]>;
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77