@fastify/cookie

Parse, Sign & Set Cookies

@fastify/cookie

The @fastify/cookie plugin adds reply.setCookie and request.cookies, with optional signing for tamper-evident values.

4 min read Level 2/5 #fastify#cookies#auth
What you'll learn
  • Install @fastify/cookie
  • Register with a secret for signing
  • Read request.cookies and set cookies with reply.setCookie

Cookies are how browsers carry session state across requests. @fastify/cookie is the canonical parser and setter — and it supports signing so clients cannot forge values.

Install & Register

npm install @fastify/cookie
import cookie from '@fastify/cookie'

await app.register(cookie, {
  secret: app.config.COOKIE_SECRET,
  hook: 'onRequest',
  parseOptions: {},
})

The secret enables HMAC signing; rotate it carefully (you can pass an array of secrets to support both old and new during rotation).

Reading Cookies

app.get('/me', async (req, reply) => {
  const raw = req.cookies.session
  if (!raw) return reply.code(401).send()
  const unsigned = req.unsignCookie(raw)
  if (!unsigned.valid) return reply.code(401).send()
  return { sessionId: unsigned.value }
})

Setting Cookies

app.post('/login', async (req, reply) => {
  // ... validate credentials ...
  reply
    .setCookie('session', 'abc123', {
      path: '/',
      httpOnly: true,
      secure: true,
      sameSite: 'lax',
      signed: true,
      maxAge: 60 * 60 * 24 * 7,
    })
    .send({ ok: true })
})

httpOnly blocks JS access, secure requires HTTPS, sameSite: 'lax' mitigates CSRF for top-level navigations.

@fastify/jwt →