Skip to main content
Bun provides native APIs for working with HTTP cookies through Bun.Cookie and Bun.CookieMap. These APIs offer fast 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.
cookies.ts

In HTTP servers

In Bun’s HTTP server, the cookies property on the request object (in routes) is an instance of CookieMap:
server.ts

Methods

get(name: string): string | null

Retrieves a cookie by name. Returns null if the cookie doesn’t exist.
get-cookie.ts

has(name: string): boolean

Checks if a cookie with the given name exists.
has-cookie.ts

set(name: string, value: string): void

set(options: CookieInit): void

Adds or updates a cookie in the map. Cookies default to { path: "/", sameSite: "lax" }.
set-cookie.ts

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.
delete-cookie.ts

toJSON(): Record<string, string>

Converts the cookie map to a serializable format.
cookie-to-json.ts

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:
iterate-cookies.ts

Properties

size: number

Returns the number of cookies in the map.
cookie-size.ts
Bun.Cookie represents an HTTP cookie with its name, value, and attributes.
cookie-class.ts

Constructors

constructors.ts

Properties

cookie-properties.ts

Methods

isExpired(): boolean

Checks if the cookie has expired.
is-expired.ts

serialize(): string

toString(): string

Returns a string representation of the cookie suitable for a Set-Cookie header.
serialize-cookie.ts

toJSON(): CookieInit

Converts the cookie to a plain object suitable for JSON serialization.
cookie-json.ts

Static methods

Parses a cookie string into a Cookie instance.
parse-cookie.ts
Factory method to create a cookie.
cookie-from.ts

Types

types.ts