Session Handling In NodeJS

Posted By : Hotam Singh | 24-Oct-2017

Session handling is very important in any kind of web application. Each application that is used to track user’s activity or manage user’s data on their server, must use sessions. As developer point of view we should know sessions and how to use sessions in web application. I am going to discuss using sessions in node.js application.

 

We will cover the following in this article:

 

  1. What is session?

  2. Ways to store session data?

  3. How to use session in Node.JS?

1  What is session?

It is a Place where we store data that you need access on every request. Every user has a unique session on a website where we visit. Sessions are basically used to store user data and access that data when needed. Sessions store data on server side instead of browsers.

 

2  Ways to store session data?

There are different ways to store session data. Some of the most popular ways to store session data are :

 

  • Store in application’s memory

  • Store in cookie

  • Store in cache memory

  • Or store in any database.

3  How to use session in Node.JS?

Installation:

 

In Node.JS, we need to install express-session module before using session in our Node.JS application. We can install express-session using the following command

 

Usage: To use express-session into our Node.JS application, Use the following syntax.

Once we include above line into our Node.JS application, we can use session into our application.

Secret: secret is a random string. It is required option to work session properly. Secret is used to encrypt browser’s cookie.

 

Resave: If set to true, it forces the session to resave even if no modifications are made on each request. If set to false, it saves to session store when any modification is done.

 

saveUninitialized: A session is called uninitialized if it is new but not modified. If this option is set to true, it forces uninitialized session to be saved.

Cookie: cookies.secure is set to be either true/false. When cookie.secure is set to be true, it accepts only https-enabled websites. If we set cookie.secure to be true and access our website over http, it will not set the cookie.

About Author

Author Image
Hotam Singh

Hotam has 1.5 years of experience in Node.JS. He has worked on Front End, JavaScript, Jquery, Backbone.JS, Database: MySQL, MongoDB. His hobbies are playing Sudoku/Puzzles and watching movies.

Request for Proposal

Name is required

Comment is required

Sending message..