Koa Session Middleware

7.0.2 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

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}`);
});

view raw JSON →