All Projects → hoangvvo → Next Session

hoangvvo / Next Session

Licence: mit
Simple promise-based session middleware for Next.js, micro, Express, and more

Programming Languages

javascript
184084 projects - #8 most used programming language
typescript
32286 projects

Projects that are alternatives of or similar to Next Session

Slim Session
A very simple session middleware for Slim Framework 2/3/4.
Stars: ✭ 200 (+24.22%)
Mutual labels:  middleware, session
Next Connect
The TypeScript-ready, minimal router and middleware layer for Next.js, Micro, Vercel, or Node.js http/http2
Stars: ✭ 454 (+181.99%)
Mutual labels:  middleware, nextjs
Connext Js
A middleware and route handling solution for Next.js.
Stars: ✭ 211 (+31.06%)
Mutual labels:  middleware, nextjs
Session
Simple session middleware for Express
Stars: ✭ 5,571 (+3360.25%)
Mutual labels:  middleware, session
Express Promise
❤️ Middleware for easy rendering of async Query results.
Stars: ✭ 320 (+98.76%)
Mutual labels:  middleware, promise
Cookie Session
Simple cookie-based session middleware
Stars: ✭ 928 (+476.4%)
Mutual labels:  middleware, session
Angular Promise Buttons
Chilled loading buttons for AngularJS
Stars: ✭ 156 (-3.11%)
Mutual labels:  promise
Next Secure Headers
Sets secure response headers for Next.js.
Stars: ✭ 156 (-3.11%)
Mutual labels:  nextjs
Vulcan Next
The Next starter for GraphQL developers
Stars: ✭ 155 (-3.73%)
Mutual labels:  nextjs
Notus Nextjs
Notus NextJS: Free Tailwind CSS UI Kit and Admin
Stars: ✭ 152 (-5.59%)
Mutual labels:  nextjs
Gramps Express
NOTE: The GrAMPS core has moved to https://github.com/gramps-graphql/gramps
Stars: ✭ 161 (+0%)
Mutual labels:  middleware
Async Busboy
Promise based multipart form parser for KoaJS
Stars: ✭ 159 (-1.24%)
Mutual labels:  promise
Actions Gh Pages
GitHub Actions for GitHub Pages 🚀 Deploy static files and publish your site easily. Static-Site-Generators-friendly.
Stars: ✭ 2,576 (+1500%)
Mutual labels:  nextjs
Koa Hbs
Handlebars templates for Koa.js
Stars: ✭ 156 (-3.11%)
Mutual labels:  middleware
Es6
ES5 vs ES6 Reference
Stars: ✭ 158 (-1.86%)
Mutual labels:  promise
Serverless Next.js
⚡ Deploy your Next.js apps on AWS Lambda@Edge via Serverless Components
Stars: ✭ 2,977 (+1749.07%)
Mutual labels:  nextjs
Next Useragent
next-useragent parses browser user-agent strings for next.js
Stars: ✭ 158 (-1.86%)
Mutual labels:  nextjs
Mande
600 bytes convenient and modern wrapper around fetch
Stars: ✭ 154 (-4.35%)
Mutual labels:  promise
Gaea
Gaea is a mysql proxy, it's developed by xiaomi b2c-dev team.
Stars: ✭ 2,123 (+1218.63%)
Mutual labels:  middleware
Next Apollo Auth
Authentication Boilerplate with Next.js and Apollo GraphQL
Stars: ✭ 159 (-1.24%)
Mutual labels:  nextjs

next-session

npm minified size CircleCI codecov PRs Welcome

Simple promise-based session middleware for Next.js. Also works in micro or Node.js HTTP Server, Express, and more.

Project status: While there will be bug fixes, it is unlikely that next-session will receive features PR in the future. Consider using alternatives like express-session+next-connect or next-iron-session instead.

Installation

// NPM
npm install next-session
// Yarn
yarn add next-session

Usage

👉 Upgrading from v1.x to v2.x? Please read the release notes here!

👉 Upgrading from v2.x to v3.x? Please read the release notes here!

next-session has several named exports:

  • session to be used as a Connect/Express middleware. (Use next-connect if used in Next.js)
  • withSession to be used as HOC in Page Components or API Routes wrapper (and several others).
  • applySession, to manually initialize next-session by providing req and res.

Use one of them to work with next-session. Can also be used in other frameworks in the same manner as long as they have (req, res) handler signature.

Warning The default session store, MemoryStore, should not be used in production since it does not persist nor work in Serverless.

API Routes

Usage in API Routes may result in API resolved without sending a response. This can be solved by either adding:

export const config = {
  api: {
    externalResolver: true,
  },
}

...or setting options.autoCommit to false and do await session.commit() (See this).

{ session }

import { session } from 'next-session';
import nextConnect from 'next-connect';

const handler = nextConnect()
  .use(session({ ...options }))
  .all(() => {
    req.session.views = req.session.views ? req.session.views + 1 : 1;
    res.send(
      `In this session, you have visited this website ${req.session.views} time(s).`
    );
  })

export default handler;

{ withSession }

import { withSession } from 'next-session';

function handler(req, res) {
  req.session.views = req.session.views ? req.session.views + 1 : 1;
  res.send(
    `In this session, you have visited this website ${req.session.views} time(s).`
  );
}
export default withSession(handler, options);

{ applySession }

import { applySession } from 'next-session';

export default async function handler(req, res) {
  await applySession(req, res, options);
  req.session.views = req.session.views ? req.session.views + 1 : 1;
  res.send(
    `In this session, you have visited this website ${req.session.views} time(s).`
  );
}

Pages

next-session does not work in Custom App since it leads to deoptimization.

{ withSession } (getInitialProps)

This will be deprecated in the next major release!

[email protected]>9.3.0 recommends using getServerSideProps instead of getInitialProps. Also, it is not reliable since req or req.session is only available on server only

import { withSession } from 'next-session';

function Page({ views }) {
  return (
    <div>In this session, you have visited this website {views} time(s).</div>
  );
}

Page.getInitialProps = ({ req }) => {
  let views;
  if (typeof window === 'undefined') {
    // req.session is only available on server-side.
    req.session.views = req.session.views ? req.session.views + 1 : 1;
    views = req.session.views;
  }
  // WARNING: On client-side routing, neither req nor req.session is available.
  return { views };
};

export default withSession(Page, options);

{ applySession } (getServerSideProps)

import { applySession } from 'next-session';

export default function Page({views}) {
  return (
    <div>In this session, you have visited this website {views} time(s).</div>
  );
}

export async function getServerSideProps({ req, res }) {
  await applySession(req, res, options);
  req.session.views = req.session.views ? req.session.views + 1 : 1;
  return {
    props: {
      views: req.session.views
    }
  }
}

Options

Regardless of the above approaches, to avoid bugs, you want to reuse the same options to in every route. For example:

// Define the option only once
// foo/bar/session.js
export const options = { ...someOptions };

// Always import it at other places
// pages/index.js
import { options } from 'foo/bar/session';
/* ... */
export default withSession(Page, options);
// pages/api/index.js
import { options } from 'foo/bar/session';
/* ... */
await applySession(req, res, 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. MemoryStore
genid The function that generates a string for a new session ID. nanoid
encode Transforms session ID before setting cookie. It takes the raw session ID and returns the decoded/decrypted session ID. undefined
decode Transforms session ID back while getting from cookie. It should return the encoded/encrypted session ID undefined
touchAfter Only touch after an amount of time. Disabled by default or if set to -1. See touchAfter. -1 (Disabled)
autoCommit Automatically commit session. Disable this if you want to manually session.commit() true
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 (in seconds) Specifies the value for the Max-Age Set-Cookie attribute. unset (Browser session)

touchAfter

Touching refers to the extension of session lifetime, both in browser (by modifying Expires attribute in Set-Cookie header) and session store (using its respective method). This prevents the session from being expired after a while.

In autoCommit mode (which is enabled by default), for optimization, a session is only touched, not saved, if it is not modified. The value of touchAfter allows you to skip touching if the session is still recent, thus, decreasing database load.

encode/decode

You may supply a custom pair of function that encode/decode or encrypt/decrypt the cookie on every request.

// `express-session` signing strategy
const signature = require('cookie-signature');
const secret = 'keyboard cat';
session({
  decode: (raw) => signature.unsign(raw.slice(2), secret),
  encode: (sid) => (sid ? 's:' + signature.sign(sid, secret) : null),
});

API

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) await req.session.destroy();

req.session.commit()

Save the session and set neccessary headers. Return Promise. It must be called before sending the headers (res.writeHead) or response (res.send, res.end, etc.).

You must call this if autoCommit is set to false.

req.session.hello = 'world';
await req.session.commit();
// always calling res.end or res.writeHead after the above

req.session.id

The unique id that associates to the current session.

req.session.isNew

Return true if the session is new.

Session Store

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

Compatibility with Express/Connect stores

To use Express/Connect stores, you may need to use expressSession from next-session if the store has the following pattern.

const session = require('express-session');
const MongoStore = require('connect-mongo')(session);

// Use `expressSession` as the replacement

import { expressSession } from 'next-session';
const MongoStore = require('connect-mongo')(expressSession);

Implementation

A compatible session store must include three functions: set(sid, session), get(sid), and destroy(sid). The function touch(sid, session) is recommended. All functions can either return Promises or allowing callback in the last argument.

// Both of the below work!

function get(sid) {
  return promiseGetFn(sid)
}

function get(sid, done) {
  cbGetFn(sid, done);
}

Contributing

Please see my contributing.md.

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].