• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

NodeJS : ExpressJS Session Management

September 11, 2015 //  by Mohamed Sanaulla//  Leave a Comment

This tutorial explains the basic concept of ExpressJS session management. Sessions are an important part of web application. HTTP being stateless, to maintain state across requests among many other approaches, sessions and cookies is one approach.

In this article we will explore how we can make use of Node package express-session to maintain session in a ExpressJS based web application.

ExpressJS and NodeJS

Setting up the app

Let us create an empty Node project using npm as shown below:

$ mkdir session-demo
$ cd session-demo
$ npm init
name: (session-demo)
version: (1.0.0)
description: Session demo for expressjs app
entry point: (index.js)
test command:
git repository:
keywords:
author: mohamed sanaulla
license: (ISC)
About to write to G:\node\session-demo\package.json:

{
  "name": "session-demo",
  "version": "1.0.0",
  "description": "Session demo for expressjs app",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "mohamed sanaulla",
  "license": "ISC"
}

Is this ok? (yes)

Install relevant node packages for Express and Express session:

$npm install express --save
$npm install express-session --save

Let us create a simple Express app as shown below:

//Filename - index.js
var express = require('express');
var session = require('express-session');

var app = express();
app.get("/", function(req, res){
  res.json({
    "status" : "ok"
  });
});

app.listen(3300, function (){
  console.log("Server started at: http://localhost:3300");
});

The above app returns a JSON object on calling http://localhost:3300/. Its a very simple example.

ExpressJS Session Management Example

In the below example, I am using session to record frequency of API invocation for a user. express-session by default stores the session data in memory. It provides support for replacing this default storage with different storage options as listed here.

express-session accepts a few properties in the options object. This object is passed while setting up the session with express app as shown below:

var express = require('express');
var session = require('express-session');
var app = express();
var sessionOptions = {};
app.use(session(sessionOptions));

Different properties of the sessions options object are:

  • cookie: Options object for the session ID cookie. The default value is { path: '/', httpOnly: true, secure: false, maxAge: null }.
  • genid: Function to generate the session ID. Default is to use uuid
  • name:The name of the session ID cookie to set in the response (and read from in the request).
  • proxy: Trust the reverse proxy when setting secure cookies.
  • resave: If true forces a session to be saved back to store even if it was not modified in the request.
  • rolling: Forces a cookie to be set on every request.
  • saveUninitialized: If true it forces a newly created session without any modifications to be saved to the session store.
  • secret: It is a required option and is used for signing the session ID cookie.
  • store: Session store instance. Default is to use memory store.
  • unset: Controls the handling of session object in the store after it is unset. Either delete or keep the session object. Default is to keep the session object

Let us update the express app code to increment the frequency of the API invocation per user and record it in the session as shown below:

var express = require('express');
var session = require('express-session');

var app = express();

var sessionOptions = {
  secret: "secret",
  resave : true,
  saveUninitialized : false
};

app.use(session(sessionOptions));

app.get("/", function(req, res){
  if ( !req.session.views){
    req.session.views = 1;
  }else{
    req.session.views += 1;
  }

  res.json({
    "status" : "ok",
    "frequency" : req.session.views
  });
});

app.listen(3300, function (){
  console.log("Server started at: http://localhost:3300");
});

Run the above application by using command: node . from the app root directory. Continuously load the URL: http://localhost:3300/ and see the frequency changing.
expressjs session management

Conclusion

  • Also Read : HOW TO : SignIn with Twitter using Node.js and Express.js

This was a very simple example of expressjs session management. I hope the expressjs session example I have provided is very helpful.  It is a pre-requiste information to be known before working on authentication related features as authentication uses session to record authenticated user info. We will also see how to use different session stores i.e mysql, MongoDB and so on.

Category: NodeJSTag: ExpressJS Tutorials

About Mohamed Sanaulla

In his day job he works on developing enterprise applications using ADF. He is also the moderator of JavaRanch forums and an avid blogger.

Previous Post: «mongodb MongoDB : GridFS Tutorial
Next Post: Spring Cache Tutorial New Features in Spring Boot 1.4»

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact