Home

Awesome

koa-session-minimal

NPM version Downloads Build Status codecov

Native Koa 2 session middleware, inspired by and compatible with koa-generic-session. This can be used as a drop-in replacement for koa-generic-session in Koa 2.

This rewrite implements koa-generic-session's essential interfaces, with around 100 lines of code in ES6. It supports existing session stores for koa-generic-session.

Version 4+ requires node 8+. Please use v3.0.4 for node versions older than 8.

Minimum features and storage usage

This middleware guarantees the following:

Installation

$ npm install koa-session-minimal

Usage

const Koa = require('koa')
const session = require('koa-session-minimal')
const redisStore = require('koa-redis')

const app = new Koa()

app.use(session({
  store: redisStore()
}))

// count middleware, increment when url = /add
app.use(async (ctx, next) => {
  ctx.session.count = ctx.session.count || 0
  if (ctx.path === '/add') ctx.session.count++

  await next()

  ctx.body = ctx.session.count
})

app.listen(3000)

Interfaces

Options

Session expiration

Default session has settings cookie.maxAge = 0 for cookie and ttl = ONE_DAY for session store, means that a session will be expired in one of the following circumstances:

With settings that cookie.maxAge > 0, the ttl for store data will be always the same as maxAge.

Dynamic session expiration (cookie options)

When setting cookie option to a plain object, all sessions will use the same cookie options. If a function is assigned to cookie, cookie options will be dynamically calculated at each (non-empty) session's saving stage. For example, you can use an arrow function to set different maxAge for user and guest sessions, as below:

session({
  cookie: ctx => ({
    maxAge: ctx.session.user ? ONE_MONTH : 0
  })
})

Session security

Middlewares are recommended to call sessionHandler.regenerateId() during authentication state change (login). This middleware provides the essential interface, It will be other middleware's decision on when and how often they want to roll the session id.

NOTE: Below is mostly copied from koa-generic-session's README, because the two middlewares share the same store interfaces. Any store that implements koa-generic-session's store interfaces should also work with koa-session-minimal. koa-redis is tested as an example in test/store_redis.test.js

Session store

You can use any other store to replace the default MemoryStore, it just needs to follow this api:

the api needs to return a Promise, Thunk, generator, or an async function.

Stores presented

License

MIT