Skip to main content

createCookie

Creates a logical container for managing a browser cookie from the server. A Cookie is a container for cookie metadata (name and options) with methods to parse and serialize cookie values.

Signature

string
required
The name of the cookie as it appears in the Cookie and Set-Cookie headers.
CookieOptions
Configuration options for the cookie.
string[]
Array of secrets used to sign/unsign cookie values. The first secret is used for signing new cookies. All secrets are tried when parsing to support secret rotation.
string
Specifies the domain for the cookie. Defaults to the current domain.
string
default:"/"
Specifies the URL path that must exist in the requested URL for the browser to send the cookie.
number
Maximum age of the cookie in seconds. Takes precedence over expires.
Date
Expiration date of the cookie. Use maxAge instead for relative expiration.
boolean
When true, the cookie is inaccessible to JavaScript’s document.cookie API.
boolean
When true, the cookie is only sent over HTTPS connections.
'lax' | 'strict' | 'none'
default:"lax"
Controls when the cookie is sent with cross-site requests.
  • "strict" - Cookie is only sent for same-site requests
  • "lax" - Cookie is sent for top-level navigations and same-site requests
  • "none" - Cookie is sent for all requests (requires secure: true)

Returns

A cookie container object with the following properties and methods:
string
The name of the cookie.
boolean
true if the cookie uses one or more secrets for signing.
Date | undefined
The expiration date of the cookie, calculated from maxAge or expires option.
function
Parses a raw Cookie header and returns the value of this cookie or null if not present.
function
Serializes a value and returns the Set-Cookie header string.

Basic Example

Extract cookie values from incoming requests:
filename=app/routes/theme.tsx
Set cookies in responses:
filename=app/routes/set-theme.tsx

Signed Cookies

Sign cookies to prevent tampering:

Secret Rotation

Rotate secrets without invalidating existing cookies:

Override Options at Runtime

You can override cookie options when serializing:
Set a cookie with past expiration:

Complex Data Types

Cookies automatically serialize and deserialize JSON:

Security Considerations

Always Sign Sensitive Cookies

Prevent tampering by signing cookies that contain important data:

Use HttpOnly for Session Cookies

Prevent XSS attacks from accessing sensitive cookies:

Secure in Production

Always enable secure in production to prevent man-in-the-middle attacks:
Browsers limit cookie size to about 4KB. For larger data, use session storage instead: