Bun 은 Bun.Cookie 와 Bun.CookieMap 을 통해 HTTP cookies 작업을 위한 네이티브 API 를 제공합니다. 이 API 는 HTTP 요청 및 응답에서 cookies 를 구문 분석하고 생성하며 조작하는 빠르고 사용하기 쉬운 메서드를 제공합니다.
CookieMap 클래스
Bun.CookieMap 은 cookies 컬렉션을 작업하기 위한 Map 유사 인터페이스를 제공합니다. Iterable 인터페이스를 구현하므로 for...of 루프 및 기타 반복 메서드와 함께 사용할 수 있습니다.
// 빈 cookie map
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 속성 (라우터에서) 은 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);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
map 에 cookie 를 추가하거나 업데이트합니다. cookies 는 기본적으로 { 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
map 에서 cookie 를 제거합니다. 응답에 적용될 때 이 메서드는 빈 문자열 값과 과거의 만료 날짜를 가진 cookie 를 추가합니다. 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 map 을 직렬화 가능한 형식으로 변환합니다.
const json = cookies.toJSON();toSetCookieHeaders(): string[]
모든 cookie 변경 사항을 적용하는 데 사용할 수 있는 Set-Cookie 헤더 값의 배열을 반환합니다.
Bun.serve() 를 사용할 때는 이 메서드를 명시적으로 호출할 필요가 없습니다. req.cookies map 에 가해진 모든 변경 사항은 자동으로 응답 헤더에 적용됩니다. 이 메서드는 주로 다른 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("서버 실행 중: http://localhost:3000/");
});2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
반복
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}`);
});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
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,
});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 - 만료 타임스탬프 (epoch 이후 ms)
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 (과거의 Date)
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