Home » Node.js

Using Session in Express.js (Node.js)

In this Node.js article, we are going to learn about sessions in Express.js, how to create sessions, how to use them in Node.js code?
Submitted by Manu Jemini, on November 25, 2017

Nothing much can be done without implementation of the session in any programming language. Whenever we need to keep the track of any data, even after the user leaves its page or even close the particular tab. fundamentally, we can understand it as storage of browser.

Express gives a nice and easy way to use session. If you are in need to know when you will really need a session, think about a login mechanism. Whenever a user has logged in, we want to make sure that for that particular user login is not needed. Saying so, we will have to same keep track for a particular user.

Now, if you keep this piece of data on your server machine, it will be very hard for us. Therefore we will keep this piece of data on the client machine. This also gives an advantage that this pretty safe to keep one’s data on one’s machine.

Getting started with sessions

  • Open your command prompt and move to the directory of your project.
  • Now enter this command npm install express-session - This will download the required node modules on your machine.

Below is a complete example of using session.

Server file

// step-1
var express = require('express');

// step-2
var app = express(); 

// step-3
app.use(
session({
 secret: 'ANYTHIG',
 cookie: { 
maxAge: 60000 
}
}));
 
// step-4
app.get('/', function(req, res) {
  if (req.session.login) {
	 res.send(true);
 } else {
res.send(false);
  }
});

// step-5
app.listen(3000,function(){
     console.log("Server is running on 3000");
})

Discussing steps that we have followed in our server file,

  • Require express module.
  • Using express.
  • Creating session.
  • Defining listener using .get method.
  • Listen on port 3000.

This is will do the job, Good luck.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.