Bun fornisce API native per lavorare con i cookie HTTP tramite Bun.Cookie e Bun.CookieMap. Queste API offrono metodi veloci e facili da usare per analizzare, generare e manipolare i cookie nelle richieste e risposte HTTP.
Classe CookieMap
Bun.CookieMap fornisce un'interfaccia simile a Map per lavorare con collezioni di cookie. Implementa l'interfaccia Iterable, permettendoti di usarla con i cicli for...of e altri metodi di iterazione.
// Mappa cookie vuota
const cookies = new Bun.CookieMap();
// Da una stringa cookie
const cookies1 = new Bun.CookieMap("name=value; foo=bar");
// Da un oggetto
const cookies2 = new Bun.CookieMap({
session: "abc123",
theme: "dark",
});
// Da un array di coppie nome/valore
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
Nei server HTTP
Nel server HTTP di Bun, la proprietà cookies sull'oggetto request (in routes) è un'istanza di CookieMap:
const server = Bun.serve({
routes: {
"/": req => {
// Accedi ai cookie della request
const cookies = req.cookies;
// Ottieni un cookie specifico
const sessionCookie = cookies.get("session");
if (sessionCookie != null) {
console.log(sessionCookie);
}
// Controlla se un cookie esiste
if (cookies.has("theme")) {
// ...
}
// Imposta un cookie, verrà applicato automaticamente alla response
cookies.set("visited", "true");
return new Response("Hello");
},
},
});
console.log("Server in ascolto su: " + 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
Metodi
get(name: string): string | null
Recupera un cookie per nome. Restituisce null se il cookie non esiste.
// Ottieni per nome
const cookie = cookies.get("session");
if (cookie != null) {
console.log(cookie);
}2
3
4
5
6
has(name: string): boolean
Controlla se esiste un cookie con il nome specificato.
// Controlla se il cookie esiste
if (cookies.has("session")) {
// Il cookie esiste
}2
3
4
set(name: string, value: string): void
set(options: CookieInit): void
set(cookie: Cookie): void
Aggiunge o aggiorna un cookie nella mappa. I cookie hanno come default { path: "/", sameSite: "lax" }.
// Imposta per nome e valore
cookies.set("session", "abc123");
// Imposta usando l'oggetto opzioni
cookies.set({
name: "theme",
value: "dark",
maxAge: 3600,
secure: true,
});
// Imposta usando l'istanza 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
Rimuove un cookie dalla mappa. Quando applicato a una Response, aggiunge un cookie con valore stringa vuota e una data di scadenza nel passato. Un cookie verrà eliminato con successo nel browser solo se il dominio e il percorso sono gli stessi di quando è stato creato.
// Elimina per nome usando dominio e percorso predefiniti.
cookies.delete("session");
// Elimina con opzioni dominio/percorso.
cookies.delete({
name: "session",
domain: "example.com",
path: "/admin",
});2
3
4
5
6
7
8
9
toJSON(): Record<string, string>
Converte la mappa cookie in un formato serializzabile.
const json = cookies.toJSON();toSetCookieHeaders(): string[]
Restituisce un array di valori per gli header Set-Cookie che possono essere usati per applicare tutte le modifiche ai cookie.
Quando si usa Bun.serve(), non è necessario chiamare esplicitamente questo metodo. Qualsiasi modifica apportata alla mappa req.cookies viene automaticamente applicata agli header della response. Questo metodo è principalmente utile quando si lavora con altre implementazioni di server 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(`Trovati ${cookies.size} cookie`);
});
server.listen(3000, () => {
console.log("Server in esecuzione su http://localhost:3000/");
});2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Iterazione
CookieMap fornisce diversi metodi per l'iterazione:
// Itera sulle voci [nome, cookie]
for (const [name, value] of cookies) {
console.log(`${name}: ${value}`);
}
// Usando entries()
for (const [name, value] of cookies.entries()) {
console.log(`${name}: ${value}`);
}
// Usando keys()
for (const name of cookies.keys()) {
console.log(name);
}
// Usando values()
for (const value of cookies.values()) {
console.log(value);
}
// Usando 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
Proprietà
size: number
Restituisce il numero di cookie nella mappa.
console.log(cookies.size); // Numero di cookieClasse Cookie
Bun.Cookie rappresenta un cookie HTTP con il suo nome, valore e attributi.
import { Cookie } from "bun";
// Crea un cookie base
const cookie = new Bun.Cookie("name", "value");
// Crea un cookie con opzioni
const secureSessionCookie = new Bun.Cookie("session", "abc123", {
domain: "example.com",
path: "/admin",
expires: new Date(Date.now() + 86400000), // 1 giorno
httpOnly: true,
secure: true,
sameSite: "strict",
});
// Analizza da una stringa cookie
const parsedCookie = new Bun.Cookie("name=value; Path=/; HttpOnly");
// Crea da un oggetto opzioni
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
Costruttori
// Costruttore base con nome/valore
new Bun.Cookie(name: string, value: string);
// Costruttore con nome, valore e opzioni
new Bun.Cookie(name: string, value: string, options: CookieInit);
// Costruttore da stringa cookie
new Bun.Cookie(cookieString: string);
// Costruttore da oggetto cookie
new Bun.Cookie(options: CookieInit);2
3
4
5
6
7
8
9
10
11
Proprietà
cookie.name; // string - Nome del cookie
cookie.value; // string - Valore del cookie
cookie.domain; // string | null - Ambito dominio (null se non specificato)
cookie.path; // string - Ambito percorso URL (default "/")
cookie.expires; // number | undefined - Timestamp di scadenza (ms dall'epoch)
cookie.secure; // boolean - Richiede HTTPS
cookie.sameSite; // "strict" | "lax" | "none" - Impostazione SameSite
cookie.partitioned; // boolean - Se il cookie è partizionato (CHIPS)
cookie.maxAge; // number | undefined - Età massima in secondi
cookie.httpOnly; // boolean - Accessibile solo via HTTP (non JavaScript)2
3
4
5
6
7
8
9
10
Metodi
isExpired(): boolean
Controlla se il cookie è scaduto.
// Cookie scaduto (Data nel passato)
const expiredCookie = new Bun.Cookie("name", "value", {
expires: new Date(Date.now() - 1000),
});
console.log(expiredCookie.isExpired()); // true
// Cookie valido (Usando maxAge invece di expires)
const validCookie = new Bun.Cookie("name", "value", {
maxAge: 3600, // 1 ora in secondi
});
console.log(validCookie.isExpired()); // false
// Cookie di sessione (nessuna scadenza)
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
Restituisce una rappresentazione stringa del cookie adatta per un header 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=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
Converte il cookie in un oggetto semplice adatto per la serializzazione 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
// }
// Funziona con JSON.stringify
const jsonString = JSON.stringify(cookie);2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Metodi statici
Cookie.parse(cookieString: string): Cookie
Analizza una stringa cookie in un'istanza 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
Metodo factory per creare un cookie.
const cookie = Bun.Cookie.from("session", "abc123", {
httpOnly: true,
secure: true,
maxAge: 3600,
});2
3
4
5
Tipi
interface CookieInit {
name?: string;
value?: string;
domain?: string;
/** Default '/'. Per consentire al browser di impostare il percorso, usa una stringa vuota. */
path?: string;
expires?: number | Date | string;
secure?: boolean;
/** Default `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