ctx.cookies
A Cookies instance for reading and writing HTTP cookies, with support for signed cookies via `app.keys`.
Syntax
ctx.cookies.get(name, [options])
ctx.cookies.set(name, [value], [options])
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
name | string | Yes | The cookie name. |
value | string | No | The cookie value. Pass `null` or omit to delete the cookie. |
options | object | No | Cookie options: `signed` (boolean), `maxAge` (ms), `expires` (Date), `httpOnly` (default true), `secure`, `sameSite`, `domain`, `path`. |
Returns
string | undefined — For `.get()`: the cookie value or `undefined`. `.set()` returns the Cookies instance.
Examples
import Koa from 'koa';
const app = new Koa();
app.keys = ['my-secret'];
app.use(async (ctx) => {
const visits = Number(ctx.cookies.get('visits') ?? 0) + 1;
ctx.cookies.set('visits', String(visits), {
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
httpOnly: true,
signed: true,
});
ctx.body = { visits };
});
app.listen(3000);
Output
Set-Cookie: visits=1; visits.sig=<hmac>; Max-Age=604800; HttpOnly
{"visits":1}
Notes
`app.keys` must be set before using `{ signed: true }`. Koa uses the
[cookies](https://github.com/pillarjs/cookies) npm package internally.
For more advanced session management, use `koa-session`.