Open In App

How to use session variable with Node.js ?

In this article, we’ll learn about how to use session variables with Node.js.

Session Management in Node.js:



 

Cookies in session management :

 

Let us take a few examples to understand this concept better :



  1. View count.
  2. Login Logout Page.

Example 1: View counter for the client. When a user visits the site. Then a cookie is assigned to the user and a session is created. The next time when a user visits, he is recognized by the cookie, and the variable gets updated.

The steps required for “View Count” are given below:

Step 1: Initialize the project using the following command in terminal 

npm init

Step 2: Install the following required modules using the terminal.

npm install express express-session cookie-parser

Step 3: Create an app.js file as given below.

Project Structure Image: Your project Structure should look like this:

 

Step 4: Write down the following code in the app.js file.




const express = require("express");
const session = require("express-session");
const cookieParser = require("cookie-parser");
const PORT = 4000;
 
const app = express();
 
// Initialization
app.use(cookieParser());
 
app.use(session({
    secret: "amar",
    saveUninitialized: true,
    resave: true
}));
 
 
app.get('/', (req, res) => {
    if (req.session.view) {
 
        // The next time when user visits,
        // he is recognized by the cookie
        // and variable gets updated.
        req.session.view++;
        res.send("You visited this page for "
            + req.session.view + " times");
    }
    else {
 
        // If user visits the site for
        // first time
        req.session.view = 1;
        res.send("You have visited this page"
           + " for first time ! Welcome....");
    }
})
 
// Host
app.listen(PORT, () =>
    console.log(`Server running at ${PORT}`));

Step 4: Run the file using the below command in the terminal.

node app.js

Output: The number of times you visit the same page, the number of times counter will increase.

 

Example 2: Suppose there are three links login, logout, and profile. The user can’t go to the profile directly until he logged in. When the user logs in the session are created and the session will be destroyed after logout. 

Approach: We are creating a login logout page. Whenever a user logs in we put that user into the session and throughout the session, user would stay in that session. When the user logs out, we will destroy the session.

The steps required for the “Login Logout Page” are given below:

Step 1:  Initialize the project and create a package.json file.    

npm init

Step 2: Install the following required modules for the project.

npm i express express-session cookie-parser

Step 3: Create an app.js file as shown below

Project Structure image: Your project Structure should look like this:

 

Step 4: Write down the following code in a given file.




const express = require("express");
const app = express();
const session = require("express-session");
const cookieParser = require("cookie-parser");
const PORT = 4000;
 
// Initialization
app.use(cookieParser());
 
app.use(session({
    secret: "amar",
    saveUninitialized: true,
    resave: true
}));
 
// User Object
 
const user = {
    name: "Amar",
    Roll_number: 43,
    Address: "Pune"
};
 
// Login page
app.get("/login", (req, res) => {
    req.session.user = user;
    req.session.save();
    return res.send("Your are logged in");
});
 
app.get("/user", (req, res) => {
    const sessionuser = req.session.user;
    res.send(sessionuser);
});
 
// Logout page
app.get("/logout", (req, res) => {
    req.session.destroy();
    res.send("Your are logged out ");
});
 
// Host
app.listen(PORT, () => console.log(`Server at ${PORT}`));

Step 5: Run the file using the following command in the terminal.

node app.js

Output:

 


Article Tags :