Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

koa-session

koajs1mMIT7.0.2TypeScript support: included

Koa cookie session middleware with external store support

koa, middleware, session, cookie

readme

koa-session

NPM version Node.js CI Test coverage Known Vulnerabilities npm download Node.js Version PRs Welcome

Simple session middleware for Koa. Defaults to cookie-based sessions and supports external stores.

Installation

npm install koa-session

Notice

7.x has a breaking change: drop Node.js < 18.19.0 support. And it support CommonJS and ESM both.

6.x changed the default cookie key from koa:sess to koa.sess to ensure set-cookie value valid with HTTP spec. See issue. If you want to be compatible with the previous version, you can manually set config.key to koa:sess.

Example

View counter example:

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

const app = new Koa();

app.keys = ['some secret hurr'];

const CONFIG = {
  key: 'koa.sess', /** (string) cookie key (default is koa.sess) */
  /** (number || 'session') maxAge in ms (default is 1 days) */
  /** '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 */
  maxAge: 86400000,
  autoCommit: true, /** (boolean) automatically commit headers (default true) */
  overwrite: true, /** (boolean) can overwrite or not (default true) */
  httpOnly: true, /** (boolean) httpOnly or not (default true) */
  signed: true, /** (boolean) signed or not (default true) */
  rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
  renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
  secure: true, /** (boolean) secure cookie*/
  sameSite: null, /** (string) session cookie sameSite options (default null, don't set it) */
};

app.use(session(CONFIG, app));
// or if you prefer all default config, just use => app.use(session(app));

app.use(ctx => {
  // ignore favicon
  if (ctx.path === '/favicon.ico') return;

  let n = ctx.session.views || 0;
  ctx.session.views = ++n;
  ctx.body = n + ' views';
});

app.listen(3000);
console.log('listening on port 3000');

API

Options

The cookie name is controlled by the key option, which defaults to "koa.sess". All other options are passed to ctx.cookies.get() and ctx.cookies.set() allowing you to control security, domain, path, and signing among other settings.

Custom encode/decode Support

Use options.encode and options.decode to customize your own encode/decode methods.

Hooks

  • valid(): valid session value before use it
  • beforeSave(): hook before save session

External Session Stores

The session is stored in a cookie by default, but it has some disadvantages:

  • Session is stored on client side unencrypted
  • Browser cookies always have length limits

    You can store the session content in external stores (Redis, MongoDB or other DBs) by passing options.store with three methods (these need to be async functions):

  • get(key, maxAge, { rolling, ctx }): get session object by key

  • set(key, sess, maxAge, { rolling, changed, ctx }): set session object for key, with a maxAge (in ms)
  • destroy(key, {ctx}): destroy session for key

    Once you pass options.store, session storage is dependent on your external store -- you can't access the session if your external store is down. Use external session stores only if necessary, avoid using session as a cache, keep the session lean, and store it in a cookie if possible!

    The way of generating external session id is controlled by the options.genid(ctx), which defaults to uuid.v4().

    If you want to add prefix for all external session id, you can use options.prefix, it will not work if options.genid(ctx) present.

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

Events

koa-session will emit event on app when session expired or invalid:

  • session:missed: can't get session value from external store.
  • session:invalid: session value is invalid.
  • session:expired: session value is expired.

Custom External Key

External key is used the cookie by default, but you can use options.externalKey to customize your own external key methods. options.externalKey with two methods:

  • get(ctx): get the external key
  • set(ctx, value): set the external key

Session#isNew

Returns true if the session is new.

if (this.session.isNew) {
  // user has not logged in
} else {
  // user has already logged in
}

Session#maxAge

Get cookie's maxAge.

Session#maxAge=

Set cookie's maxAge.

Session#externalKey

Get session external key, only exist when external session store present.

Session#save()

Save this session no matter whether it is populated.

Session#manuallyCommit()

Session headers are auto committed by default. Use this if autoCommit is set to false.

Destroying a session

To destroy a session simply set it to null:

this.session = null;

License

MIT

Contributors

Contributors

Made with contributors-img.

changelog

Changelog

7.0.2 (2025-01-19)

Bug Fixes

  • make sure options instance is not mutated (#230) (c45bf8b)

7.0.1 (2025-01-19)

Bug Fixes

7.0.0 (2025-01-19)

⚠ BREAKING CHANGES

  • drop Node.js < 18.19.0 support

Features

6.4.0 / 2023-02-04

features

6.3.1 / 2023-01-03

fixes

6.3.0 / 2023-01-03

features

others

6.2.0 / 2021-03-30

features

6.1.0 / 2020-10-08

features

others

fixes

  • [d34fc8e] - fix: RFC6265 compliant default cookie name (#197) (zacanger <zac@zacanger.com>)
    • [BREAKING CHANGE]: Default cookie is now koa.sess rather than koa:sess

5.13.1 / 2020-02-01

fixes

5.13.0 / 2020-02-01

features

5.12.3 / 2019-08-23

fixes

5.12.2 / 2019-07-10

fixes

5.12.1 / 2019-07-10

fixes

5.12.0 / 2019-05-17

features

  • [39ca830] - feat: add the parameter "ctx" to the function "genid" so can get the … (#173) (松松 <1733458402@qq.com>)

others

5.11.0 / 2019-04-29

features

fixes

others

5.10.1 / 2018-12-18

features

fixes

5.10.0 / 2018-10-29

features

5.9.0 / 2018-08-28

features

5.8.3 / 2018-08-22

fixes

others

5.8.2 / 2018-07-12

fixes

  • [c487944] - fix: Fixes a bug that reset the cookie expire date to the default (1 day) when using browser sessions (maxAge: 'session') (#117) (Adriano <adrianocola@gmail.com>)

others

5.8.1 / 2018-01-17

fixes

5.8.0 / 2018-01-17

features

5.7.1 / 2018-01-11

fixes

5.7.0 / 2018-01-09

features

5.6.0 / 2018-01-09

features

5.5.1 / 2017-11-17

others

5.5.0 / 2017-08-04

features

5.4.0 / 2017-07-03

  • feat: opts.genid (#87)

5.3.0 / 2017-06-17

  • feat: support rolling (#84)

5.2.0 / 2017-06-15

  • feat: support options.ContextStore (#81)

5.1.0 / 2017-06-01

  • Create capability to create cookies that expire when browser is close… (#77)

5.0.0 / 2017-03-12

  • feat: async/await support (#70)

4.0.1 / 2017-03-01

  • fix: ctx.session should be configurable (#67)

4.0.0 / 2017-02-27

  • [BREAKING CHANGE]: Drop support for node < 4.
  • [BREAKING CHANGE]: Internal implementations are changed, so some private API is changed.
    • Change private api session.save(), won't set cookie immediately now.
    • Remove private api session.changed().
    • Remove undocumented property context.sessionKey, can use opts.key instead.
    • Change undocumented property context.sessionOptions to getter.
  • feat: Support external store by pass options.store.
  • feat: Throw when encode session error, consider a breaking change.
  • feat: Clean cookie when decode session throw error, ensure next request won't throw again.
  • fix: Customize options.decode will check expired now
  • docs: Remove Semantics in README because it's not "guest" sessions any more

3.4.0 / 2016-10-15

  • fix: add 'session' name for middleware function (#58)
  • chore(package): update dependencies
  • readme: ignore favicon in example

3.3.1 / 2015-07-08

  • code: fix error in variable referencing

3.3.0 / 2015-07-07

  • custom encode/decode support

3.2.0 / 2015-06-08

  • feat: add opts.valid() and opts.beforeSave() hooks

3.1.1 / 2015-06-04

  • deps: upgrade deep-equal to 1.0.0
  • fix: allow get session property before enter session middleware

3.1.0 / 2014-12-25

  • add session.maxAge
  • set expire in cookie value

3.0.0 / 2014-12-11

  • improve performance by reduce hiddin class on every request
  • refactor with commit() helper
  • refactor error handling with finally statement

2.0.0 / 2014-02-17

  • changed cookies to be base64-encoded (somewhat breaks backwards compatibility)

1.2.1 / 2014-02-04

  • fix saving sessions when a downstream error is thrown

1.2.0 / 2013-12-21

  • remove sid from docs
  • remove uid2 dep
  • change: only save new sessions if populated
  • update to use new middleware signature

1.1.0 / 2013-11-15

  • add change check, removing the need for .save()
  • add sane defaults. Closes #4
  • add session clearing support. Closes #9
  • remove public .save()