next-session
Simple promise-based session middleware for Next.js.
** This is WIP **.
Installation
// NPM
npm install next-session
// Yarn
yarn add next-session
Usage
:point_right: Upgrading from v1.x to v2.x? Please read the release notes here!
:point_right: Upgrading from v2.x to v3.x? Please read the release notes here!
const session = require('next-session');
app.use(session(opts));
API
session(options)
options
next-session
accepts the properties below.
options | description | default |
---|
name | The name of the cookie to be read from the request and set to the response. | sid |
store | The session store instance to be used. You must specify the store to be used. Several stores can be found in lib/stores . | null (required) |
genid | The function that generates a string for a new session ID. | crypto.randomBytes(16).toString('hex') |
rolling | Force the cookie to be set on every request despite no modification, which extends the life time of the cookie in the browser | false |
touchAfter | Only touch the session store after an amount of time, except when the session is modified, to decrease database load. Setting the value to -1 will disable touch() . | 0 (Touch every time) |
cookie.secure | Specifies the boolean value for the Secure Set-Cookie attribute. | false |
cookie.httpOnly | Specifies the boolean value for the httpOnly Set-Cookie attribute. | true |
cookie.path | Specifies the value for the Path Set-Cookie attribute. | / |
cookie.domain | Specifies the value for the Domain Set-Cookie attribute. | unset |
cookie.sameSite | Specifies the value for the SameSite Set-Cookie attribute. | unset |
cookie.maxAge | Specifies the value for the Max-Age Set-Cookie attribute. | unset (Session) |
req.session
This allows you to set or get a specific value that associates to the current session.
if (loggedIn) req.session.user = 'John Doe';
const currentUser = req.session.user;
req.session.destroy()
Destroy to current session and remove it from session store.
if (loggedOut) req.session.destroy();
req.session.id
The unique id that associates to the current session.
Session Store
The session store to use for session middleware (see options
above).
Unlike libraries such as express-session
, next-session
does not default to a store. You must specify a session store or use one from next-session/lib/stores
.
Implementation
A compatible session store must extend from ./src/store
and include three functions: set(sid)
, get(sid)
, and destroy(sid)
. The function touch(sid, session)
is recommended. The store may emit store.emit('disconnect')
or store.emit('connect')
to inform its readiness.
All functions should return Promises (callbacks are not supported). For an example of a session store implementation, see MemoryStore
.
Stores that use callbacks will be promisified using util.promisify
.
Compatible stores
Make a PR to add your own compatible stores here.
Contributing
Please see my contributing.md.
License
MIT