Koa Session Middleware
koa-session is a robust session middleware designed for the Koa.js web framework, enabling the management of user sessions within Koa applications. By default, it stores session data directly in HTTP cookies, offering a straightforward approach for many use cases. However, it also provides extensive support for integrating external session stores, which is crucial for overcoming limitations associated with client-side cookie storage, such as size constraints and potential security concerns from unencrypted client-side data. The current stable version is 7.0.2, released in January 2025, demonstrating active development and maintenance with recent bug fixes following major releases. Version 7.0.0 notably introduced dual CommonJS and ES module support and raised the minimum Node.js requirement to 18.19.0. Its key differentiators include deep integration into the Koa ecosystem, a highly configurable API for cookie options, and extensible hooks for custom session validation and pre-save logic, making it a versatile solution for session management in modern Koa applications.
Common errors
-
Error [ERR_REQUIRE_ESM]: require() of ES Module ... from ... not supported.
cause Attempting to use CommonJS `require()` syntax with `koa-session` version 7.x in an environment where the project is configured as an ES module, or attempting to import a dependency that is now ESM-only.fixIf your project is an ES module, use `import session from 'koa-session';`. If your project is CommonJS and you are experiencing this with a dependency, ensure `koa-session` is compatible with your other dependencies or configure your build system for interop. -
TypeError: this.app.keys is missing, please set `app.keys`.
cause The Koa application instance's `keys` property has not been set or is empty. This property is mandatory for signing cookies, which `koa-session` relies on for secure sessions.fixBefore `app.use(session(CONFIG, app));`, add `app.keys = ['your_strong_secret_key'];` with one or more secure, randomly generated keys. -
Session not persisting across requests or `ctx.session` is undefined after upgrading.
cause This often occurs after upgrading from `koa-session` versions older than 6.x to 6.x or newer due to the default cookie key changing from `koa:sess` to `koa.sess`.fixTo fix this and maintain existing sessions, manually set the `key` option in your session configuration back to the old default: `{ key: 'koa:sess', ... }`. -
Invalid cookie header for 'koa.sess'
cause A malformed cookie or an issue with cookie parsing, possibly related to incorrect characters in the cookie value, which can happen if encryption/decryption fails or the session data is corrupted.fixEnsure `app.keys` is correctly set and consistent across restarts. Check your session data for any unusual characters. If using an external store, verify its data integrity. Also, review any custom `encode`/`decode` functions for errors.
Warnings
- breaking Version 7.0.0 dropped support for Node.js versions older than 18.19.0. Applications running on older Node.js versions will need to upgrade or remain on a `koa-session` v6.x release.
- gotcha The default cookie key changed from `koa:sess` to `koa.sess` in version 6.x to comply with HTTP cookie specifications. Upgrading from versions older than 6.x will result in existing sessions becoming invalid unless explicitly configured.
- gotcha By default, `koa-session` stores session data directly in encrypted cookies on the client side. While encrypted, the data is still transmitted with every request. For large session data or sensitive information, using an external session store (e.g., Redis, MongoDB) is recommended to keep data server-side.
- gotcha The `app.keys` property *must* be set on your Koa application instance for `koa-session` to function correctly, as it's used for signing session cookies. Failure to set `app.keys` will result in sessions not being signed, making them vulnerable to tampering and often leading to `ctx.session` being undefined.
- gotcha The `secure` cookie option should be set to `true` in production environments to ensure cookies are only sent over HTTPS. The `sameSite` option should also be configured (e.g., `lax` or `strict`) for enhanced security against CSRF attacks. Misconfiguration can lead to security vulnerabilities.
Install
-
npm install koa-session -
yarn add koa-session -
pnpm add koa-session
Imports
- session
const session = require('koa-session');import session from 'koa-session';
- Koa
const Koa = require('koa');import Koa from 'koa';
- Session
import { Session } from 'koa-session';import type { Session, SessionOptions, Store } from 'koa-session';
Quickstart
import Koa from 'koa';
import session from 'koa-session';
const app = new Koa();
// IMPORTANT: Set app.keys for signed cookies. Without this, sessions will not work.
app.keys = ['your secret key']; // Replace with a strong, secure key or array of keys
const CONFIG = {
key: 'koa.sess', // cookie key, defaults to 'koa.sess'
maxAge: 86400000, // 1 day in ms
autoCommit: true, // automatically commit headers (default true)
overwrite: true, // can overwrite or not (default true)
httpOnly: true, // httpOnly or not (default true)
signed: true, // signed or not (default true)
rolling: false, // Force a session identifier cookie to be set on every response (default false)
renew: false, // renew session when nearly expired (default false)
secure: process.env.NODE_ENV === 'production', // Use secure cookies in production
sameSite: 'lax' // Recommended for security: 'lax' or 'strict'
};
app.use(session(CONFIG, app));
app.use(ctx => {
if (ctx.path === '/favicon.ico') return;
let n = ctx.session.views || 0;
ctx.session.views = ++n;
ctx.body = n + ' views';
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});