Understanding koa-session: Concepts, Source Code Walkthrough, and External Store Implementations
This article explains the fundamentals of cookies and sessions, provides a detailed analysis of the koa-session source code, demonstrates how to configure and use koa-session with in‑memory, Redis, and MySQL stores, and summarizes security considerations and performance trade‑offs.
This article introduces the basic concepts of cookies and sessions used in web applications. Cookies are small text files stored on the client to identify a user and maintain a session, while a session is a server‑side object that keeps user data across requests.
It then describes how Koa handles sessions through the koa-session middleware, outlining the initialization process, the interaction between cookies and external storage, and the lifecycle of a session object.
Code Structure
├── index.js // entry point
├── lib
│ ├── context.js // core logic for different storage types
│ ├── session.js // session initialization
│ └── util.js // utility functions
└── package.jsonBasic Usage Example
var session = require('./');
var Koa = require('koa');
var app = new Koa();
const keys = ["key"]; // signed key
const CONGIG = {
key: 'koa:sess', // cookie key (default koa:sess)
maxAge: 4000, // session expiration in ms
autoCommit: true, // auto‑commit to response header
overwrite: true, // allow overwrite
httpOnly: true, // HttpOnly prevents JS access
signed: true, // sign the cookie
rolling: true, // refresh each response
renew: false // refresh when near expiration
};
app.keys = keys;
app.use(session(CONGIG, app));
app.use((ctx, next) => {
if ('/favicon.ico' == ctx.path) return;
var n = ctx.session.views || 0;
ctx.session.views = ++n;
ctx.body = n + ' views';
});
app.listen(3000);
console.log('listening on port 3000');The middleware initializes the session, attaches ctx.session , and on each request updates the view count.
Method Analysis
The article walks through key functions such as extendContext , the session middleware itself, initFromExternal , initFromCookie , _shouldSaveSession , and save . It explains how the middleware decides whether to store the session in memory, an external store, or a cookie, and how it determines when to commit changes based on flags like rolling , renew , and hash comparisons.
External Store Implementations
Redis Example
var session = require('koa-session');
var Koa = require('koa');
var redisStore = require('koa-redis');
var Redis = require('ioredis');
var app = new Koa();
var redisClient = new Redis({ host: '127.0.0.1', port: 6379 });
const sessStore = redisStore({ client: redisClient });
app.keys = ['key', 'keys'];
let CONGIG = {
key: 'session',
prefix: 'session',
store: sessStore,
};
app.use(session(CONGIG, app));
app.use((ctx, next) => {
if ('/favicon.ico' == ctx.path) return;
var n = ctx.session.views || 0;
ctx.session.views++;
ctx.body = n + ' views';
});
app.listen(3000);
console.log('listening on port 3000');Running the above with Redis shows the generated session key and stored JSON data.
MySQL Example
const session = require('koa-session-minimal');
var Koa = require('koa');
var MysqlStore = require('koa-mysql-session');
var app = new Koa();
var config = {
user: 'root',
password: '981010',
database: 'sys',
host: '127.0.0.1',
port: 3306,
};
app.keys = ['some secret hurr'];
const CONFIG = {
key: 'USER_SID',
store: new MysqlStore(config),
};
app.use(session(CONFIG, app));
app.use((ctx, next) => {
if ('/favicon.ico' == ctx.path) return;
var n = ctx.session.views || 0;
ctx.session.views = ++n;
ctx.body = n + ' views';
next();
});
app.listen(3000);The MySQL store automatically creates a table _mysql_session_store to persist session data.
Summary
Sessions are simply objects that can be stored in cookies, memory, or any external storage the developer implements. Security considerations include base64 encoding, the httpOnly flag, and signed cookies to prevent tampering. Performance trade‑offs involve the overhead of database access versus the risk of exposing user data in cookies; Redis is commonly used for fast, persistent session storage.
Beike Product & Technology
As Beike's official product and technology account, we are committed to building a platform for sharing Beike's product and technology insights, targeting internet/O2O developers and product professionals. We share high-quality original articles, tech salon events, and recruitment information weekly. Welcome to follow us.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.