Registry / web-framework / koa-session

koa-session

JSON →
library7.0.2jsnpmunverified

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.

npm install koa-session
INSTALL
IMPORT
SIG · KOA-SESSION
K
koa-session
web-frameworkjavascriptv7.0.2
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

session
import session from 'koa-session';
const session = require('koa-session');
Since v7.0.0, both ESM and CommonJS are supported, but ESM import is preferred for new projects. `require()` still works for CommonJS.
Koa
import Koa from 'koa';
const Koa = require('koa');
Koa is a peer dependency and commonly used alongside koa-session. Its import style should match your project's module system.
Session
import type { Session, SessionOptions, Store } from 'koa-session';
import { Session } from 'koa-session';
Import types using `import type` for TypeScript to avoid bundling issues. `Session`, `SessionOptions`, and `Store` are common types for extending functionality.

This quickstart demonstrates a basic Koa application using koa-session to track page views, illustrating essential setup with cookie-based sessions, `app.keys` configuration, and common session options.

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}`); });
Debug
Known issues
breakingVersion 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.
fix
Upgrade your Node.js environment to version 18.19.0 or newer. If an upgrade is not possible, use `koa-session` version 6.x or earlier.
affects: >=7.0.0
gotchaThe 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.
fix
To maintain compatibility with old sessions, set the `key` option in your session configuration to `koa:sess` (e.g., `key: 'koa:sess'`). For new deployments, `koa.sess` is recommended.
affects: >=6.0.0
gotchaBy 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.
fix
Configure an external `store` option for `koa-session` to persist session data on the server. Implement a custom store or use a community-maintained store package (e.g., `koa-redis-store`).
affects: >=1.0.0
gotchaThe `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.
fix
Ensure `app.keys` is an array of secret strings (e.g., `app.keys = ['very secret key', 'another secret key']`) or a single string. Use strong, randomly generated keys and manage them securely (e.g., via environment variables).
affects: >=1.0.0
gotchaThe `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.
fix
In your `koa-session` configuration, set `secure: true` and `sameSite: 'lax'` (or `'strict'` depending on your needs) for production. Example: `secure: process.env.NODE_ENV === 'production', sameSite: 'lax'`.
affects: >=1.0.0
Errors
Common errors & fixes
Error [ERR_REQUIRE_ESM]: require() of ES Module ... from ... not supported.
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.
fix
If 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`.
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.
fix
Before `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.
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`.
fix
To 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'
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.
fix
Ensure `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.
Upgrade
Version history
7.0.2latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
9 hits · last 30 days
node
8
OpenAI (training)
1
Resources