How key rotation works
mainTo support key rotation, pass an array of keys to the key option.
- Signing: The library always signs and encrypts new sessions using the first key in the array.
- Decoding: If decoding fails with the first key, the library attempts to decode using every subsequent key in the array.
- Automatic Rotation: When a session is successfully decoded using an older key (one not at index 0), the library automatically re-signs the cookie with the newest key (the first key in the array) upon the next request. This improves performance for subsequent calls.
Best Practice: It is recommended to keep only 2 keys in the array at a time to minimize the performance cost of multiple decode attempts during a rotation period.
const key1 = fs.readFileSync(path.join(__dirname, 'secret-key1'))
const key2 = fs.readFileSync(path.join(__dirname, 'secret-key2'))
fastify.register(require('@fastify/secure-session'), {
// key1 is the new key used for signing
// key2 is the old key used for fallback decoding
key: [key1, key2],
cookie: {
path: '/'
}
})