3.1.1 • Public • Published


npm version

@goa/session is Session Middleware for Goa apps written in ES6 and optimised with JavaScript Compiler. It is used in the Idio web server.

yarn add @goa/session

Fork Diff

This package is a fork of koa-session with a number of improvements:

  1. The session middleware constructor does not require the app, and will not extend the context with .session property, if middleware wasn't explicitly used. Fixes 177 to avoid confusion when .session is not expected to be present, but is read from cookies anyway.
  2. Remove crc32 hash checking which was unnecessary. Fixes 161 as JSON comparison is enough.
  3. Fix the bug when initial maxAge is not set on the initial session cookie, resulting in a session-only sessions.

Table Of Contents


The package is available by importing its default function:

import session from '@goa/session'

  opts=: !SessionConfig,
): !_goa.Middleware

Initialize the session middleware with opts.

  • opts !SessionConfig (optional): The configuration passed to koa-session.

The interface is changed from the original package, so that the app is always passed as the first argument.

SessionConfig: Configuration for the session middleware.

Name Type & Description Default
key string koa:sess
The cookie key.
maxAge (string | number) 86400000
maxAge in ms with default of 1 day. Either a number or 'session'. session will result in a cookie that expires when session/browser is closed. Warning: If a session cookie is stolen, this cookie will never expire.
overwrite boolean true
Can overwrite or not.
httpOnly boolean true
httpOnly or not.
signed boolean true
Signed or not.
autoCommit boolean true
Automatically commit headers.
store ExternalStore -
You can store the session content in external stores (Redis, MongoDB or other DBs) by passing an instance of a store with three methods (these need to be async functions).
externalKey { get: function(_goa.Context): string, set: function(_goa.Context, string): void } -
When using a store, the external key is recorded in cookies by default, but you can use options.externalKey to customize your own external key methods.
ContextStore new (arg0: !_goa.Context) => ExternalStore
If your session store requires data or utilities from context, opts.ContextStore can be used to set a constructor for the store that implements the ExternalStore interface.
prefix string -
If you want to add prefix for all external session id. It will not work if options.genid(ctx) present.
rolling boolean false
Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown.
renew boolean false
Renew session when session is nearly expired, so we can always keep user logged in.
valid (ctx: !_goa.Context, sess: !Object) => boolean
The validation hook: valid session value before use it.
beforeSave (ctx: !_goa.Context, sess: !KoaSession) => boolean
The hook before save session.
genid (ctx: !_goa.Context) => string
The way of generating external session id.
encode (sess: !Object) => string
Use options.encode and options.decode to customize your own encode/decode methods.
decode (sess: string) => !Object
Use options.encode and options.decode to customize your own encode/decode methods.


import aqt from '@rqt/aqt'
import Goa from '@goa/koa'
import session from '@goa/session'

const app = new Goa()
app.keys = ['g', 'o', 'a']
app.use(session({ signed: false })) // normally, signed should be true

app.use((ctx) => {
  if (ctx.path == '/set') {
    ctx.session.message = 'hello'
    ctx.body = 'You have cookies now:'
  } else if (ctx.path == '/exit') {
    ctx.session = null
    ctx.body = 'Bye'
  else ctx.body = `Welcome back: ${ctx.session.message}`

app.listen(async function() {
  const { port } = this.address()
  const url = `http://localhost:${port}`

  // 1. Acquire cookies
  let { body, headers } = await aqt(`${url}/set`)
  console.log(body, headers, '\n')
  const cookie = headers['set-cookie']

  // 2. Exploit cookies
  ;({ body, headers } = await aqt(url, {
    headers: {
  console.log(body, headers, '\n')

  // 3. Destroy cookies
  ;({ body, headers } = await aqt(`${url}/exit`, {
    headers: {
  console.log(body, headers)

You have cookies now: { 'content-type': 'text/plain; charset=utf-8',
  'content-length': '21',
   [ 'koa:sess=eyJtZXNzYWdlIjoiaGVsbG8iLCJfZXhwaXJlIjoxNTc4NjY2NDgzNjc4LCJfbWF4QWdlIjo4NjQwMDAwMH0=; path=/; expires=Fri, 10 Jan 2020 14:28:03 GMT; httponly' ],
  date: 'Thu, 09 Jan 2020 14:28:03 GMT',
  connection: 'close' } 

Welcome back: hello { 'content-type': 'text/plain; charset=utf-8',
  'content-length': '19',
  date: 'Thu, 09 Jan 2020 14:28:03 GMT',
  connection: 'close' } 

Bye { 'content-type': 'text/plain; charset=utf-8',
  'content-length': '3',
   [ 'koa:sess=; path=/; expires=Fri, 10 Jan 2020 14:28:03 GMT; httponly' ],
  date: 'Thu, 09 Jan 2020 14:28:03 GMT',
  connection: 'close' }

If your session store requires data or utilities from context, opts.ContextStore is also supported. ContextStore must be a class which implements three instance methods demonstrated below. new ContextStore(ctx) will be executed on every request.

ExternalStore: By implementing this class, the session can be recorded and retrieved from an external store (e.g., a database), instead of cookies.

Name Type & Description
constructor new () => ExternalStore
Constructor method.
get (key: string, maxAge: (number | string), opts: { rolling: boolean }) => !Promise<!Object>
Get session object by key.
set (key: string, sess: !Object, maxAge: (number | string), opts: { rolling: boolean, changed: boolean }) => !Promise
Set session object for key, with a maxAge (in ms, or as 'session').
destroy (key: string) => !Promise
Destroy session for key.
Show an example external store.
const sessions = {}

export default {
  async get(key) {
    return sessions[key]

  async set(key, value) {
    sessions[key] = value

  async destroy(key) {
    sessions[key] = undefined

The session object itself (ctx.session) has the following methods.

Session: The session instance accessible via Goa's context.

Name Type Description
isNew* boolean Returns true if the session is new.
populated* boolean Populated flag, which is just a boolean alias of .length.
maxAge* (number | string) Get/set cookie's maxAge.
save* () => void Save this session no matter whether it is populated.
manuallyCommit* () => !Promise<void> Session headers are auto committed by default. Use this if autoCommit is set to false.
KoaSession extends Session: A private session model.
Name Type & Description
constructor new (sessionContext: KoaContextSession, obj?: { _maxAge: (number | undefined), _session: (boolean | undefined) }) => KoaSession
Private session constructor. It is called one time per request by the session context when middleware accesses .session property of the context.
_expire number
Private JSON serialisation.
_requireSave boolean
Private JSON serialisation.
_sessCtx KoaContextSession
Private JSON serialisation.
_ctx _goa.Context
Private JSON serialisation.


This package is meant to be used as part of the Idio web server. But it also can be used on its own with Koa. To enable auto-completions when configuring the middleware, please install typedefs, and import them in your application entry:

Package & Link Import

npm version

const sess = session({
  // you can access ctx as context now
  valid(ctx, obj) {
    // force presence of a key in headers too
    const s = ctx.get('secret-key')
    return obj['secret-key'] == s
// at the bottom of the file
 * @typedef {import('@typedefs/goa').Context} _goa.Context
This will add information about required types to VSCode. This is required because even though session's configuration object is described with JSDoc in its file, VSCode has a bug that does not allow propagation of imported types so they need to be imported manually like above.

Usage Events

This middleware integrates with Idio that collects middleware usage statistics to reward package maintainers. It will emit certain events to bill its usage:

  1. save: When the session is saved via cookies.
  2. save-external: When the session is saved via external storage.

The usage is recorded via the ctx.neoluddite context property set by a server such as Idio. In future, more fine-grained usage events might appear.

Copyright & License

GNU Affero General Public License v3.0

Affero GPL means that you're not allowed to use this middleware on the web unless you release the source code for your application. This is a restrictive license which has the purpose of defending Open Source work and its creators.

Please refer to the Idio license agreement for more info on dual-licensing. You're allowed to use this middleware without disclosing the source code if you sign up on neoluddite.dev package reward scheme.

Original Work by dead-horse and contributors under MIT license.

Art Deco © Art Deco for Idio 2020 Idio Tech Nation Visa Tech Nation Visa Sucks



Package Sidebar


npm i @goa/session



Weekly Downloads






Unpacked Size

182 kB

Total Files


Last publish


  • zvr