Implement key rotation for signed cookies
mainTo rotate signing keys without invalidating existing cookies, provide an Array of keys to the secret option in the plugin configuration.
Behavior:
- The plugin always uses the first key in the array (
keys[0]) to sign new cookies. - When parsing, the plugin iterates through the array to find a key that can successfully decode the signed cookie.
- To complete a rotation, you must redeploy the server with a new
secretarray containing the new key at index 0 and the old key at index 1.
Best Practice: Renewing cookies during rotation
When a cookie is successfully unsigned but identified as being signed with an old key (result.renew === true), you should re-set the cookie so it is signed with the current primary key.
// Registering with multiple keys for rotation
fastify.register(require('@fastify/cookie'), {
secret: [key1, key2]
})
// Renewing a cookie signed with an old key
fastify.get('/', (req, reply) => {
const result = reply.unsignCookie(req.cookies.myCookie)
if (result.valid && result.renew) {
reply.setCookie('myCookie', result.value, {
domain: 'example.com',
path: '/',
signed: true
})
}
})