Bun.Cookie and Bun.CookieMap. These APIs offer fast, easy-to-use methods for parsing, generating, and manipulating cookies in HTTP requests and responses.
CookieMap class
Bun.CookieMap provides a Map-like interface for working with collections of cookies. It implements the Iterable interface, allowing you to use it with for...of loops and other iteration methods.
In HTTP servers
In Bun’s HTTP server, thecookies property on the request object (in routes) is an instance of CookieMap:
Methods
get(name: string): string | null
Retrieves a cookie by name. Returns null if the cookie doesn’t exist.
has(name: string): boolean
Checks if a cookie with the given name exists.
set(name: string, value: string): void
set(options: CookieInit): void
set(cookie: Cookie): void
Adds or updates a cookie in the map. Cookies default to { path: "/", sameSite: "lax" }.
delete(name: string): void
delete(options: CookieStoreDeleteOptions): void
Removes a cookie from the map. When applied to a Response, this adds a cookie with an empty string value and an expiry date in the past. A cookie will only delete successfully on the browser if the domain and path is the same as it was when the cookie was created.
toJSON(): Record<string, string>
Converts the cookie map to a serializable format.
toSetCookieHeaders(): string[]
Returns an array of values for Set-Cookie headers that can be used to apply all cookie changes.
When using Bun.serve(), you don’t need to call this method explicitly. Any changes made to the req.cookies map are automatically applied to the response headers. This method is primarily useful when working with other HTTP server implementations.
node-server.js
Iteration
CookieMap provides several methods for iteration:
Properties
size: number
Returns the number of cookies in the map.
Cookie class
Bun.Cookie represents an HTTP cookie with its name, value, and attributes.
Constructors
Properties
Methods
isExpired(): boolean
Checks if the cookie has expired.
serialize(): string
toString(): string
Returns a string representation of the cookie suitable for a Set-Cookie header.
toJSON(): CookieInit
Converts the cookie to a plain object suitable for JSON serialization.
Static methods
Cookie.parse(cookieString: string): Cookie
Parses a cookie string into a Cookie instance.