How to use session variable with Node.js ? – GeeksforGeeks

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:

  • Session Management is a technique that keeps track of users’ states (data).
  • If the client sends a request to the server then it is followed by HTTP protocol.
  • HTTP is a stateless protocol.
  • Stateless protocol means the server forgets about the client and treats every request as a new request.
  • The state is managed by the session management techniques.

Cookies in session management :

  • A cookie is a session management technique.
  • Cookies are stored as key-value pairs in clients’ browsers during requests.
  • A cookie is a way for the server or website to remember you.
  • A Cookie is small textual data that is sent by the server to a browser.
  • When the browser sends a request to the server, the server will create a session on the server side. When the server responds to the browser, cookies are sent with a response to the browser.
  • After that, if a user sends a request to the server, a cookie is sent along with it.
  • For eg. whenever you take admission to the college you have to register and after registering, you are given an ID or receipt. The second time when you go to college, you are recognized by your ID or fee receipt and you don’t need to register again.

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.

Javascript




const express = require("express");

const session = require("express-session");

const cookieParser = require("cookie-parser");

const PORT = 4000;

 

const app = express();

 

app.use(cookieParser());

 

app.use(session({

    secret: "amar",

    saveUninitialized: true,

    resave: true

}));

 

 

app.get('/', (req, res) => {

    if (req.session.view) {

 

        

        

        

        req.session.view++;

        res.send("You visited this page for "

            + req.session.view + " times");

    }

    else {

 

        

        

        req.session.view = 1;

        res.send("You have visited this page"

           + " for first time ! Welcome....");

    }

})

 

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.

Javascript




const express = require("express");

const app = express();

const session = require("express-session");

const cookieParser = require("cookie-parser");

const PORT = 4000;

 

app.use(cookieParser());

 

app.use(session({

    secret: "amar",

    saveUninitialized: true,

    resave: true

}));

 

 

const user = {

    name: "Amar",

    Roll_number: 43,

    Address: "Pune"

};

 

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);

});

 

app.get("/logout", (req, res) => {

    req.session.destroy();

    res.send("Your are logged out ");

});

 

app.listen(PORT, () => console.log(`Server at ${PORT}`));



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

node app.js

Output:

My Personal Notes

arrow_drop_up