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

Package detail

@curveball/session

curveball29.2kMIT1.0.1TypeScript support: included

Session storage using HTTP cookies

http, framework, nodejs, typescript, curveball, session, cookies, cookie

readme

Curveball Session Middleware

This package adds support for sessions to the Curveball framework.

Features:

  • It's lazy. It will only start a session if there is something in the store.
  • It will also automatically wipe the session data if session data was emptied.
  • It provides features for generating and validating CSRF tokens.

Installation

npm install @curveball/session

Upgrading from versions 0.5 and below

If you are upgrading from a 0.5.x release or earlier, this package introduces a BC break since 0.6.

In 0.5 session data was available in ctx.state.session and ctx.state.sessionId, but this has been moved to ctx.session and ctx.sessionId.

Getting started

Adding the middleware

import session from '@curveball/session';

app.use(session({
  store: 'memory',
});

This will add the in-memory session store to curveball. This store is mostly meant for testing.

Here is another example with more options:

import session from '@curveball/session';

app.use(session({
  store: 'memory',
  cookieName: 'MY_SESSION',
  expiry: 7200,
  cookieOptions: {
    secure: true,
    path: '/',
    sameSite: true,
  },
});
  • cookieName - Updates the name of the HTTP Cookie. It's CB by default.
  • expiry - The number of seconds of inactivity before the session disappears. this is 3600 seconds by default. It only pertains to the longevity of the session in the store, it doesn't influence cookie parameters.
  • cookieOptions - If set, override cookie options from the default. The list of supported options can be found in the documentation of the [cookie package][3].

Using the session store

In your own controllers and middlewares, you can set and update session data via the ctx.session property.

app.use( ctx => {

  // Running this will create the session
  ctx.session = { userId: 5 };
  ctx.response.body = 'Hello world';

});

Deleting a session

To delete an open session, just clear the session data:

app.use( ctx => {

  // Running this will create the session
  ctx.session = null;

});

Re-generate a session id.

If you clear the session id, but there is still data, the middleware will remove the old session and automatically create a new session id:

app.use( ctx => {

  // This will kill the old session and start a new one with the same data.
  ctx.sessionId = null;

});

CSRF token support

To obtain a CSRF token for forms, the middleware provides a getCsrf() function:

app.use( async ctx => {

  // Obtain a CSRF token for HTML forms:
  const csrfToken = await ctx.getCsrf();

});

It's recommended to embed this token in HTML forms as such:

<input type="hidden" name="csrf-token" value="....token goes here" />

Then on POST requests, you can easily validate the token with the validateCsrf function. If the token was incorrect, this will automatically result in a 403 error:

app.use(route.post('/form-submit', ctx => {

  // Throws error if csrf-token was not supplied or incorrect
  ctx.validateCsrf();

}));

API

It's desirable to create your own stores for product usage. Eventually this project will probably add a few more default stores.

Until then, you must implement the following interface:

interface SessionStore {

  set(id: string, values: SessionValues, expire: number): Promise<void>;
  get(id: string): Promise<SessionValues>,
  delete(id: string): Promise<void>,
  newSessionId(): Promise<string>,

}

SessionValues is simply a key->value object. expire is expressed as a unix timestamp.

changelog

Changelog

1.0.1 (2024-11-06)

  • Update to 'cookie' package v1.

1.0.0 (2024-01-17)

  • Finally! Curveball v1. Only took 6 years.
  • CommonJS support has been dropped. The previous version of this library supported both CommonJS and ESM. The effort of this no longer feels worth it. ESM is the future, so we're dropping CommonJS.
  • Now requires Node 18.
  • Upgraded to Typescript 5.3.

0.10.0 (2023-10-04)

  • The getCsrf function is no longer an async function, and returns the token immediately.
  • A warning is now emitted if getCsrf is called after the session has already been stored.

0.9.0 (2023-02-14)

  • This package now supports ESM and CommonJS modules.
  • No longer supports Node 14. Please use Node 16 or higher.

0.8.1 (2022-10-11)

  • Session data was not stored if a later middleware threw an uncaught exception. This middleware now uses finally to ensure that session data always gets stored, and the Set-Cookie header always gets sent.

0.8.0 (2022-09-03)

  • Upgraded from @curveball/core to @curveball/kernel.

0.7.0 (2022-03-21)

  • Removed expires option, and added maxAge instead. expires never made sense, because it represents a fixed point in time. Which means that if expires was set to 1 hour in the future, the middleware would no longer generate valid sessions after the first hour the server is up. (@defrex)
  • Dropped Node 12 support. Node 14 is now the minimum version.

0.6.3 (2022-03-09)

  • Added 'close' method to Memory session store, so users may cleanup open timeouts. (@defrex)
  • Updated everything to latest curveball standards.

0.6.2 (2021-03-01)

  • Export SessionStore.

0.6.1 (2021-02-02)

  • Session data should be typed as Record<string, any> not Record<string, string>.

0.6.0 (2021-02-02)

  • Major BC break: session information is now stored in ctx.session instead of ctx.state.session.
  • Adding features for CSRF token generation and checking: ctx.getCsrf and ctx.validateCsrf.
  • Typescript target is now es2019 instead of esnext to ensure that older Node.js versions are supported.
  • Switched to eslint.

0.5.0 (2020-01-22)

  • Changed the default setting for SameSite to Lax.

0.4.2 (2020-01-05)

  • Allow installation on Curveball 0.10.

0.4.1 (2019-11-11)

  • Allow 'sameSite' to be set to cookieOptions.

0.4.0 (2019-11-11)

  • Allow cookieOptions to be overridden.
  • Curveball is now a peerDependency

0.3.3 (2019-09-12)

  • Update to Curveball 0.9 API

0.3.2 (2019-03-26)

  • Stricter typescript errors.

0.3.1 (2019-03-26)

  • Update to latest dependencies.

0.3.0 (2019-10-04)

  • Updated to latest Curveball API.

0.2.0 (2018-09-24)

  • Expire sessions.
  • Add garbage collector to MemoryStore.
  • BC break: Now uses ctx.state.session and ctx.state.sessionId instead of ctx.state.session.data and ctx.state.session.id.

0.1.1 (2018-09-06)

  • SameSite and HttpOnly are both turned on.

0.1.0 (2018-09-06)

  • First version. Ships with a 'memory store'.