app.keys

Sets the array of signed cookie keys used by `ctx.cookies` for HMAC signing and verification.

Since Koa 2 Spec ↗

Syntax

app.keys = [key1, key2, ...]

Parameters

NameTypeRequiredDescription
keys string[] Yes An array of secret strings (or a Keygrip-compatible object) used to sign and verify cookies. The first key is the current signing key; older keys allow graceful rotation.

Returns

void — Setter; returns nothing.

Throws

  • Error — A signed cookie is requested but `app.keys` has not been set.

Examples

import Koa from 'koa';

const app = new Koa();
app.keys = ['supersecret-key-v2', 'supersecret-key-v1'];

app.use(async (ctx) => {
  ctx.cookies.set('session', 'abc123', { signed: true });
  ctx.body = 'Cookie set';
});

app.listen(3000);
Output
Set-Cookie: session=abc123; session.sig=<hmac>; Path=/; HttpOnly

Notes

Key rotation: put the newest key first and keep older keys to validate existing cookies while migrating. Under the hood Koa uses the [Keygrip](https://github.com/crypto-utils/keygrip) library. Never commit keys to source control; load them from environment variables.

See also