Skip to main content
Type-safe cookie parsing and serialization for Remix. It supports secure signing, secret rotation, and complete cookie attribute control.

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

npm i remix

Usage

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),
  },
})

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 a secrets option to the createCookie() function. Secret rotation is also supported, so you can easily rotate in new secrets without breaking existing cookies.
import { createCookie } 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),
  },
})
The createCookie() function accepts an options object with the following properties:
interface CookieOptions {
  /** Cookie name */
  name?: string
  
  /** Domain for the cookie */
  domain?: string
  
  /** Expiration date (Date object or UTC string) */
  expires?: Date | string
  
  /** HttpOnly flag (prevents JavaScript access) */
  httpOnly?: boolean
  
  /** Max age in seconds */
  maxAge?: number
  
  /** Path for the cookie */
  path?: string
  
  /** SameSite policy */
  sameSite?: 'Strict' | 'Lax' | 'None'
  
  /** Secure flag (HTTPS only) */
  secure?: boolean
  
  /** Secret keys for signing (enables signing if provided) */
  secrets?: string[]
  
  /** Custom encoding function */
  encode?: (value: string) => string
  
  /** Custom decoding function */
  decode?: (value: string) => string
}

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.
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.

Parsing Cookies

Parse cookies from the request’s Cookie header:
import { createCookie } from 'remix/cookie'

let userPrefsCookie = createCookie('user_prefs')

async function handler(request: Request) {
  let cookieHeader = request.headers.get('Cookie')
  let userPrefs = await userPrefsCookie.parse(cookieHeader)
  
  return Response.json({
    theme: userPrefs?.theme || 'light',
    language: userPrefs?.language || 'en',
  })
}

Serializing Cookies

Serialize cookie values to set in the response’s Set-Cookie header:
import { createCookie } from 'remix/cookie'

let userPrefsCookie = createCookie('user_prefs', {
  maxAge: 60 * 60 * 24 * 365, // 1 year
  httpOnly: true,
  secure: true,
  sameSite: 'lax',
})

async function handler(request: Request) {
  let formData = await request.formData()
  
  let prefs = {
    theme: formData.get('theme'),
    language: formData.get('language'),
  }
  
  return new Response('Preferences updated', {
    headers: {
      'Set-Cookie': await userPrefsCookie.serialize(prefs),
    },
  })
}

Security Best Practices

Always Sign Sensitive Cookies

For cookies that contain sensitive data (like session IDs), always enable signing:
let sessionCookie = createCookie('session', {
  secrets: [process.env.SESSION_SECRET],
  httpOnly: true,
  secure: true,
  sameSite: 'lax',
})

Use Secure Flag in Production

Always set the secure flag to true in production to ensure cookies are only sent over HTTPS:
let cookie = createCookie('data', {
  secure: process.env.NODE_ENV === 'production',
})

Set HttpOnly for Auth Cookies

Prevent client-side JavaScript from accessing authentication cookies:
let authCookie = createCookie('auth', {
  httpOnly: true, // Important!
  secrets: [process.env.AUTH_SECRET],
  secure: true,
})

Use SameSite for CSRF Protection

Protect against CSRF attacks by setting the sameSite attribute:
let cookie = createCookie('data', {
  sameSite: 'lax', // or 'strict' for stricter protection
})

API Reference

createCookie(name, options?)

Creates a cookie instance with the specified name and options. Parameters:
  • name: string - The cookie name
  • options?: CookieOptions - Cookie configuration options
Returns: Cookie A cookie instance with methods for parsing and serialization. Properties:
  • name: string - The cookie name
  • signed: boolean - Whether the cookie is signed
  • expires: Date | undefined - Expiration date
  • httpOnly: boolean - HttpOnly flag
  • maxAge: number | undefined - Max age in seconds
  • path: string - Cookie path
  • sameSite: 'Strict' | 'Lax' | 'None' | undefined - SameSite policy
  • secure: boolean - Secure flag
Methods:
  • parse(cookieHeader: string | null): Promise<any> - Parse cookie value from Cookie header
  • serialize(value: any): Promise<string> - Serialize cookie value for Set-Cookie header
  • headers - Type-safe HTTP header manipulation
  • session - Session management using cookies
  • fetch-router - Build HTTP routers using the web fetch API

Build docs developers (and LLMs) love