This answer assumes you are using Express or Koa, two of the most popular node.js web frameworks.
In your application, you probably have a line that says the following.
Express 4
var app = require( 'express' )() var session = require( 'express-session' ) app.use( session() )
KoaJS
var app = require( 'koa' )() var session = require( 'koa-session' ) app.use( session() )
The guiding wisdom in web applications is to make it a stateless side of the world. This means that your node.js server does not contain information between requests and can be destroyed and rebooted at any time.
A session is a very stateful state . Because of this, you need to store session data in something designed to save the data without distortion in the end. This is most often done through a database (more secure) or a browser cookie (less secure).
The express-session module contains session information in default memory. This violates stateless ideals and loses session information on reboot.
The koa-session module uses cookies by default. This is unparalleled, but causes some security concerns, as users can change their own session variables, so do not use them for billing or other sensitive operations.
In both of the above modules, you can override the default values ββin your own session store.
Redis Session Storage
I usually store session data in a database like redis .
Express
This can be easily connected to the expression using a module such as connect-redis .
Quote from Readme:
var session = require('express-session'); var RedisStore = require('connect-redis')(session); app.use(session({ store: new RedisStore(options), secret: 'keyboard cat' }));
KoaJS
Using redis to store session data is also possible in koa using the koa-redis module . Paraphrasing from the Readme:
var app require('koa')(); var session = require('koa-generic-session'); var redisStore = require('koa-redis'); app.keys = ['keys', 'keykeys']; app.use(session({ store: redisStore() })); app.use(function *() { this.session.name = 'koa-redis'; });
No Database Session Storage
Express
Express can store session data in cookies with the extension cookie-session .
Koa
As mentioned earlier, the koa-session module saves sessions in cookies by default.