koa-session
Cookie-based session middleware for Koa with optional external store support (Redis, Postgres, etc.).
Syntax
import session from 'koa-session';
app.keys = [...];
app.use(session([options], app));
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
options | object | No | Session options: `key` (cookie name, default `"koa.sess"`), `maxAge` (ms or `"session"`, default 1 day), `httpOnly` (default true), `signed` (default true), `rolling` (refresh on each request), `store` (external session store interface with `get`, `set`, `destroy`). |
app | Application | Yes | The Koa application instance (required for cookie signing via `app.keys`). |
Returns
function — Koa middleware that populates `ctx.session` on each request.
Examples
import Koa from 'koa';
import session from 'koa-session';
const app = new Koa();
app.keys = ['session-secret'];
app.use(session({ maxAge: 86400_000 }, app));
app.use(async (ctx) => {
if (ctx.path === '/login') {
ctx.session.userId = 42;
ctx.body = { loggedIn: true };
} else {
ctx.body = { userId: ctx.session.userId ?? null };
}
});
app.listen(3000);
Output
POST /login → {"loggedIn":true} + Set-Cookie: koa.sess=...
GET / → {"userId":42}
// Destroy session on logout
app.use(async (ctx) => {
if (ctx.path === '/logout') {
ctx.session = null;
ctx.body = { loggedOut: true };
}
});
Output
POST /logout → {"loggedOut":true}
Notes
By default, session data is stored in the cookie itself (signed and
base64-encoded). For large session payloads or server-side invalidation,
use an external store such as `koa-session` with a Redis adapter. Session
cookies are `HttpOnly` and signed with `app.keys` by default.