koa-encrypted-session

raw JSON →
3.0.7 verified Sat Apr 25 auth: no javascript

Encrypted cookie-based session middleware for Koa, built on top of koa-session. Current stable version is 3.0.7, targeting Node.js >=16. It uses libsodium's Secret key box for encryption, providing a scalable, stateless alternative to server-side session stores. Unlike other Koa session middlewares, it eliminates the need for a database or external cache. Key differentiator: client-side encryption using sodium-native, with support for both a high-entropy secretKey or a passphrase+salt combination. Release cadence: maintenance mode with occasional dependency updates.

error Error: secretKey must be a Buffer
cause Passing a string or non-Buffer value for secretKey option.
fix
Use Buffer.from(key, 'base64') for base64-encoded keys or Buffer.from(key, 'hex') for hex keys.
error TypeError: Cannot read properties of undefined (reading 'session')
cause Middleware not applied or app not passed as second argument.
fix
Ensure app.use(encryptedSession(options, app)) is called with app as second argument.
error ERR_REQUIRE_ESM: require() of ES Module not supported
cause Using CommonJS require() with ESM-only package.
fix
Use import instead, or use dynamic import().
breaking v3 dropped CommonJS support; ESM-only.
fix Convert to ESM or use dynamic import() if in a CommonJS project.
breaking v3 requires Node.js >=16.
fix Upgrade Node.js to v16 or later.
gotcha secretKey must be a Buffer of 32 bytes (e.g., from crypto.randomBytes(32)). Using passphrase+salt is slower and less secure.
fix Generate a key using the provided CLI tool: koa-encrypted-session-gen-key
gotcha Inherited from koa-session: must pass app as second argument to middleware.
fix Always call middleware with (options, app).
gotcha Session data is limited by cookie size (max 4KB). Large session data may cause cookie overflow.
fix Store only minimal data in session; use external store for larger payloads.
npm install koa-encrypted-session
yarn add koa-encrypted-session
pnpm add koa-encrypted-session

Sets up encrypted cookie sessions with a secret key from environment variable and tracks view count per session.

import Koa from 'koa';
import encryptedSession from 'koa-encrypted-session';

const app = new Koa();

app.use(encryptedSession({
  key: 'session',
  maxAge: 7 * 24 * 3600 * 1000,
  secretKey: Buffer.from(process.env.SESSION_SECRET_KEY ?? 'EsAg64LMvGITBBz1ZGLfDNU/MYqGDpTzJ1u4BsvIfTw=', 'base64')
}, app));

app.use(ctx => {
  ctx.session.count = (ctx.session.count ?? 0) + 1;
  ctx.body = `views: ${ctx.session.count}`;
});

app.listen(3000);