{"id":17136,"library":"koa-session","title":"Koa Session Middleware","description":"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.","status":"active","version":"7.0.2","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/koajs/session","tags":["javascript","koa","middleware","session","cookie","typescript"],"install":[{"cmd":"npm install koa-session","lang":"bash","label":"npm"},{"cmd":"yarn add koa-session","lang":"bash","label":"yarn"},{"cmd":"pnpm add koa-session","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Since v7.0.0, both ESM and CommonJS are supported, but ESM import is preferred for new projects. `require()` still works for CommonJS.","wrong":"const session = require('koa-session');","symbol":"session","correct":"import session from 'koa-session';"},{"note":"Koa is a peer dependency and commonly used alongside koa-session. Its import style should match your project's module system.","wrong":"const Koa = require('koa');","symbol":"Koa","correct":"import Koa from 'koa';"},{"note":"Import types using `import type` for TypeScript to avoid bundling issues. `Session`, `SessionOptions`, and `Store` are common types for extending functionality.","wrong":"import { Session } from 'koa-session';","symbol":"Session","correct":"import type { Session, SessionOptions, Store } from 'koa-session';"}],"quickstart":{"code":"import Koa from 'koa';\nimport session from 'koa-session';\n\nconst app = new Koa();\n\n// IMPORTANT: Set app.keys for signed cookies. Without this, sessions will not work.\napp.keys = ['your secret key']; // Replace with a strong, secure key or array of keys\n\nconst CONFIG = {\n  key: 'koa.sess', // cookie key, defaults to 'koa.sess'\n  maxAge: 86400000, // 1 day in ms\n  autoCommit: true, // automatically commit headers (default true)\n  overwrite: true, // can overwrite or not (default true)\n  httpOnly: true, // httpOnly or not (default true)\n  signed: true, // signed or not (default true)\n  rolling: false, // Force a session identifier cookie to be set on every response (default false)\n  renew: false, // renew session when nearly expired (default false)\n  secure: process.env.NODE_ENV === 'production', // Use secure cookies in production\n  sameSite: 'lax' // Recommended for security: 'lax' or 'strict'\n};\n\napp.use(session(CONFIG, app));\n\napp.use(ctx => {\n  if (ctx.path === '/favicon.ico') return;\n\n  let n = ctx.session.views || 0;\n  ctx.session.views = ++n;\n  ctx.body = n + ' views';\n});\n\nconst port = process.env.PORT || 3000;\napp.listen(port, () => {\n  console.log(`Listening on port ${port}`);\n});","lang":"typescript","description":"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."},"warnings":[{"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.","message":"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.","severity":"breaking","affected_versions":">=7.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=6.0.0"},{"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`).","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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).","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"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'`.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"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.","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.","error":"Error [ERR_REQUIRE_ESM]: require() of ES Module ... from ... not supported."},{"fix":"Before `app.use(session(CONFIG, app));`, add `app.keys = ['your_strong_secret_key'];` with one or more secure, randomly generated 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.","error":"TypeError: this.app.keys is missing, please set `app.keys`."},{"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', ... }`.","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`.","error":"Session not persisting across requests or `ctx.session` is undefined after upgrading."},{"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.","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.","error":"Invalid cookie header for 'koa.sess'"}],"ecosystem":"npm","meta_description":null}