packages/cookie/README.md
Type-safe cookie parsing and serialization for Remix. It supports secure signing, secret rotation, and complete cookie attribute control.
npm i remix
import { createCookie } from 'remix/cookie'
let sessionCookie = createCookie('session', {
httpOnly: true,
secrets: ['s3cret1'],
secure: true,
})
cookie.name // "session"
cookie.httpOnly // true
cookie.secure // true
cookie.signed // true
// Get the value of the "session" cookie from the request's `Cookie` header
let value = await sessionCookie.parse(request.headers.get('Cookie'))
// Set the value of the cookie in a Response's `Set-Cookie` header
let response = new Response('Hello, world!', {
headers: {
'Set-Cookie': await sessionCookie.serialize(value),
},
})
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 a secrets option to the Cookie constructor.
Secret rotation is also supported, so you can easily rotate in new secrets without breaking existing cookies.
import { Cookie } from 'remix/cookie'
// Start with a single secret
let sessionCookie = createCookie('session', {
secrets: ['secret1'],
})
console.log(sessionCookie.signed) // true
let response = new Response('Hello, world!', {
headers: {
'Set-Cookie': await sessionCookie.serialize(value),
},
})
All cookies sent in this scenario will be signed with the secret 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.
let sessionCookie = createCookie('session', {
secrets: ['secret2', 'secret1'],
})
// This works for cookies signed with either secret
let value = await sessionCookie.parse(request.headers.get('Cookie'))
// Newly serialized cookies will be signed with the new secret
let response = new Response('Hello, world!', {
headers: {
'Set-Cookie': await sessionCookie.serialize(value),
},
})
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.
let sessionCookie = createCookie('session', {
encode: (value) => value,
decode: (value) => value,
})
This can be useful for viewing the value of cookies in a human-readable format in the browser's developer tools. But you should be sure that the cookie value contains only characters that are valid in a cookie value.
headers - Type-safe HTTP header manipulationfetch-router - Build HTTP routers using the web fetch APInode-fetch-server - Build HTTP servers on Node.js using the web fetch APISee LICENSE