Socket
Socket
Sign inDemoInstall

next-session

Package Overview
Dependencies
Maintainers
1
Versions
37
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

next-session

Simple promise-based session middleware for Next.js


Version published
Weekly downloads
8.5K
increased by9.38%
Maintainers
1
Weekly downloads
 
Created
Source

next-session

Build Status Coverage Status

Simple promise-based session middleware for Next.js.

Installation

npm install next-session

Usage

See a real-life usage in nextjs-mongodb-app.

import session from 'next-session';

const handler = (req, res) => {
  if (req.session.views) {
    //  On later visits, increase # of views by one on every request
    req.session.views += 1;
  } else {
    //  On first visit, set # of views to 1
    req.session.views = 1;
  }
  res.send(`In this session, you have visited this website ${req.session.views} time(s).`)
};

//  wrap handler with session middleware and include options
export default session(handler, {
  name: 'sid',
  touchAfter: '6 months',
  cookies: {
    secure: true,
    maxAge: '2 years',
  },
});

Using global middleware

In reality, you would not want to wrap session() around handler in every function. You may run into situation where configuration of one session() is different from other. One solution is to create a global middleware.

Create middleware.js.

import session from 'next-session';

const middleware = handler => session(your(other(middlewares(handler))), { ...options});

export default middleware;

In each API Route, import and wrap middleware instead.

import middleware from 'path/to/your/middleware';

const handler = (req, res) => {
  //  your handle
};

export default middleware(handler);

Usage with getInitialProps

This is a temporary implementation for getInitialProps. Please be aware that it will be different in the next major version.

next-session may be used in getInitialProps by await calling useSession with arguments of req and res.

import { useSession } from 'next-session';

const Page = () => {
  //  React components
}

Page.getInitialProps = async ({ req, res }) => {
  await useSession(req, res);
  if (req.session.views) {
    //  On later visits, increase # of views by one on every request
    req.session.views += 1;
  } else {
    //  On first visit, set # of views to 1
    req.session.views = 1;
  }
  return {
    views: req.session.views
  }
}

API

session(handler, options)

Create a session middleware for handler with the given options.

handler

See Next.js 9 API Routes.

options

next-session accepts the properties below.

optionsdescriptiondefault
nameThe name of the cookie to be read from the request and set to the response.sessionId
storeThe session store instance to be used.MemoryStore
storePromisifyPromisify stores that are callback based. This allows you to use next-session with Connect stores (ex. used in express-session)false
generateIdThe function to generate a new session ID. This needs to return a string.crypto.randomBytes(16).toString('hex')
rollingForce the cookie to be set on every request despite no modification, extending the life time of the cookie in the browserfalse
touchAfterOn every request, the session store extends the life time of the session even when no changes are made (The same is done to Cookie). However, this may increase the load of the database. Setting this value will ask the store to only do so an amount of time since the Cookie is touched, with exception that the session is modified. Setting the value to -1 will disable touch().0 (Touch every time)
cookie.secureSpecifies the boolean value for the Secure Set-Cookie attribute. If set to true, cookie is only sent to the server with an encrypted request over the HTTPS protocol.false
cookie.httpOnlySpecifies the boolean value for the httpOnly Set-Cookie attribute. If set to true, cookies are inaccessible to client-side scripts. This is to help mitigate cross-site scripting (XSS) attacks.true
cookie.pathSpecifies the value for the Path Set-Cookie attribute. This indicates a URL path that must exist in the requested URL in order to send the Cookie header/
cookie.domainSpecifies the value for the Domain Set-Cookie attribute. Only allowed hosts to receive the cookie. If unspecified, it defaults to the host of the current document location, excluding subdomains. If Domain is specified, then subdomains are always included.unset
cookie.sameSiteSpecifies the value for the SameSite Set-Cookie attribute. This lets servers require that a cookie shouldn't be sent with cross-site (where Site is defined by Domain attribute) requests, which provides some protection against cross-site request forgery attacks ( CSRF).unset
cookie.maxAgeSpecifies the value for the Max-Age Set-Cookie attribute. Determine the length of time before the cookies expire. If unspecified, the cookies will expire when the client closes (Session cookies).unset (Session)

*For touchAfter and cookie.maxAge, you may use the following keywords: years (365 days), months (30 days), days, hours, minutes, seconds. If a number with none of the keywords above is provided, it will be assumed to be miliseconds. Ex: 9 months 10 days.

req.session

This allows you to set or get a specific value that associates to the current session.

//  Set a value
if (loggedIn) req.session.user = 'John Doe';
//  Get a value
const currentUser = req.session.user; // "John Doe"
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. This should not be modified.

Session Store

The session store to use for session middleware (see options above).

Implementation

A compatible session store must include three functions: set(sid), get(sid), and destroy().

All functions should return Promises (callbacks are not supported). For an example of a session store implementation, see MemoryStore.

Stores that return callbacks may be used by setting storePromisify to true.

Compatible stores

Make a PR to add your own compatible stores here.

May be used with storePromisify: true : express-session compatible stores

Contributing

Please see my contributing.md.

License

MIT

Keywords

FAQs

Package last updated on 14 Aug 2019

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc