Features
- Secure Cookie Signing: Built-in cryptographic signing using HMAC-SHA256 to prevent cookie tampering
- Secret Rotation Support: Seamlessly rotate signing secrets while maintaining backward compatibility
- Web Standards Compliant: Built on Web Crypto API and standard cookie parsing, making it runtime-agnostic
Installation
Usage
Signing Cookies
This library supports signing cookies, which is useful for ensuring the integrity of the cookie value and preventing tampering. Signing happens automatically when you provide asecrets option to the createCookie() function.
Secret rotation is also supported, so you can easily rotate in new secrets without breaking existing cookies.
secret1. Later, when it’s time to rotate secrets, add a new secret to the beginning of the array and all existing cookies will still be able to be parsed.
Cookie Options
ThecreateCookie() function accepts an options object with the following properties:
Custom Encoding
By default,encodeURIComponent and decodeURIComponent are used to encode and decode the cookie value. This is suitable for most use cases, but you can provide your own functions to customize the encoding and decoding of the cookie value.
Working with Cookie Values
Parsing Cookies
Parse cookies from the request’sCookie header:
Serializing Cookies
Serialize cookie values to set in the response’sSet-Cookie header:
Security Best Practices
Always Sign Sensitive Cookies
For cookies that contain sensitive data (like session IDs), always enable signing:Use Secure Flag in Production
Always set thesecure flag to true in production to ensure cookies are only sent over HTTPS:
Set HttpOnly for Auth Cookies
Prevent client-side JavaScript from accessing authentication cookies:Use SameSite for CSRF Protection
Protect against CSRF attacks by setting thesameSite attribute:
API Reference
createCookie(name, options?)
Creates a cookie instance with the specified name and options.
Parameters:
name: string- The cookie nameoptions?: CookieOptions- Cookie configuration options
Cookie
Cookie
A cookie instance with methods for parsing and serialization.
Properties:
name: string- The cookie namesigned: boolean- Whether the cookie is signedexpires: Date | undefined- Expiration datehttpOnly: boolean- HttpOnly flagmaxAge: number | undefined- Max age in secondspath: string- Cookie pathsameSite: 'Strict' | 'Lax' | 'None' | undefined- SameSite policysecure: boolean- Secure flag
parse(cookieHeader: string | null): Promise<any>- Parse cookie value from Cookie headerserialize(value: any): Promise<string>- Serialize cookie value for Set-Cookie header
Related Packages
headers- Type-safe HTTP header manipulationsession- Session management using cookiesfetch-router- Build HTTP routers using the web fetch API