new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Bun · Runtime · all subjects

bun apis/cookies

27 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Cookie APIs: Bun.Cookie and Bun.CookieMap

Bun provides Bun.Cookie and Bun.CookieMap for cookie handling.

CookieMap.get() method

The get(name: string) method retrieves a cookie by name from the CookieMap. It returns the cookie value as a string or null if the cookie does not exist.

CookieMap.has() method

The has(name: string) method checks if a cookie with the given name exists in the CookieMap. It returns a boolean value.

CookieMap.set() method signatures

CookieMap.set() has three signatures: set(name: string, value: string) to set by name and value, set(options: CookieInit) to set using an options object, or set(cookie: Cookie) to set using a Cookie instance. Cookies default to { path: "/", sameSite: "lax" }.

CookieMap.delete() method signatures

CookieMap.delete() has multiple signatures: delete(name: string) to delete by name using default domain and path, delete(options: CookieStoreDeleteOptions) to delete with domain/path options, or delete(name: string, options: Omit<CookieStoreDeleteOptions, "name">) to delete by name with additional options. When applied to a Response, this adds a cookie with an empty string value and an expiry date in the past. The browser only deletes the cookie if the domain and path match the ones it was created with.

CookieMap.toJSON() method

The toJSON() method converts the CookieMap to a serializable format, returning Record<string, string>.

CookieMap.toSetCookieHeaders() method

The toSetCookieHeaders() method returns an array of values for Set-Cookie headers that apply all cookie changes. Use this with HTTP servers other than Bun.serve(). In Bun.serve(), changes made to req.cookies are automatically applied to response headers.

CookieMap iteration methods

CookieMap provides iteration methods: entries() returns an IterableIterator of [name, value] pairs, keys() returns an IterableIterator of cookie names, values() returns an IterableIterator of cookie values, forEach(callback) calls the callback with (value, name, map), and CookieMap is iterable via for...of loops that yield [name, value] pairs.

CookieMap.size property

The size property returns a number representing the count of cookies in the CookieMap.

Bun.Cookie constructor signatures

Bun.Cookie has four constructor signatures: new Bun.Cookie(name: string, value: string) for a basic cookie, new Bun.Cookie(name: string, value: string, options: CookieInit) for a cookie with options, new Bun.Cookie(cookieString: string) to parse from a cookie string, and new Bun.Cookie(options: CookieInit) to create from an options object.

Cookie properties

A Cookie instance has the following properties: name (string, read-only), value (string), domain (string | null, defaults to null if not specified), path (string, defaults to "/"), expires (Date | undefined), secure (boolean), sameSite ("strict" | "lax" | "none"), partitioned (boolean), maxAge (number | undefined, in seconds), and httpOnly (boolean).

Cookie.isExpired() method

The isExpired() method checks if the cookie has expired. When both maxAge and expires are set, maxAge takes precedence, as required by RFC 6265. A non-positive maxAge value (like 0) expires the cookie immediately.

Cookie.serialize() and toString() methods

Both serialize() and toString() return a string representation of the cookie suitable for a Set-Cookie header. They produce identical output including all cookie attributes like Domain, Path, Expires, Secure, HttpOnly, and SameSite.

Bun.CookieMap constructor signatures

Bun.CookieMap can be constructed in four ways: empty with `new Bun.CookieMap()`, from a cookie string with `new Bun.CookieMap("name=value; foo=bar")`, from an object with `new Bun.CookieMap({session: "abc123", theme: "dark"})`, or from an array of name/value pairs with `new Bun.CookieMap([["session", "abc123"], ["theme", "dark"]])`.

Cookie.parse() static method

Cookie.parse(cookieString: string) is a static method that parses a cookie string into a Cookie instance. It extracts the name, value, and all attributes from the cookie string.

Cookie.from() static factory method

Cookie.from(name: string, value: string, options?: CookieInit) is a static factory method to create a Cookie instance with a name, value, and optional CookieInit options.

CookieInit interface

The CookieInit interface contains optional properties: name (string), value (string), domain (string), path (string, defaults to '/'), expires (number | Date | string), secure (boolean), sameSite ("strict" | "lax" | "none", defaults to 'lax'), httpOnly (boolean), partitioned (boolean), and maxAge (number in seconds).

CookieStoreDeleteOptions interface

The CookieStoreDeleteOptions interface contains required property name (string) and optional properties domain (string | null) and path (string).

CookieSameSite type

CookieSameSite is a type that can be one of three string values: "strict", "lax", or "none".

Request cookies in Bun.serve

In Bun's HTTP server, the cookies property on the request object is an instance of CookieMap. Any changes made to req.cookies are automatically applied to the response headers without needing to call toSetCookieHeaders().

Using CookieMap with Node.js HTTP server

When using CookieMap with Node's http.createServer, create a CookieMap from the request cookie header, make changes, and then use cookies.toSetCookieHeaders() to get an array of Set-Cookie header values to pass to res.writeHead().

Cookie.toJSON() method

The toJSON() method converts the cookie to a CookieInit plain object suitable for JSON serialization. It includes all cookie properties and works with JSON.stringify().

Read cookies from request

Read cookies from incoming requests using the cookies property on the BunRequest object. Use req.cookies.get("name") to retrieve a cookie value by name.

Set cookies with options

Use the set method on the CookieMap to set cookies: req.cookies.set(name, value, options). Supported options include maxAge (in seconds), httpOnly, secure, and path.

Delete cookies

Use the delete method on request.cookies to delete a cookie: req.cookies.delete(name, options). Deleted cookies become a Set-Cookie header on the response with the Expires attribute set to a date in the past and an empty value. The options parameter can include path.

Cookie example: reading, setting, deleting

Example showing cookie operations: Bun.serve({ routes: { "/profile": req => { const userId = req.cookies.get("user_id"); const theme = req.cookies.get("theme") || "light"; return Response.json({ userId, theme, message: "Profile page" }); }, "/login": req => { const cookies = req.cookies; cookies.set("user_id", "12345", { maxAge: 60 * 60 * 24 * 7, httpOnly: true, secure: true, path: "/" }); cookies.set("theme", "dark"); return new Response("Login successful"); }, "/logout": req => { req.cookies.delete("user_id", { path: "/" }); return new Response("Logged out successfully"); } } });

BunRequest cookies property

The BunRequest object exposes a cookies property, which is a CookieMap for reading and modifying cookies. When using routes, Bun.serve() automatically tracks calls to request.cookies.set and applies them to the response.

Give your agent this brain