The Wayback Machine - https://web.archive.org/web/20241122222255/https://www.geeksforgeeks.org/how-to-use-session-variable-with-node-js/
Open In App

How to Use Session Variables with Node.js?

Last Updated : 02 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Session management is a crucial aspect of web application development, enabling you to store user data between HTTP requests. In Node.js, session management is often handled using the express-session middleware. This article will guide you through the process of setting up and using session variables in a Node.js application.

Session Management

Session management in Node.js involves the crucial task of maintaining users’ states or data throughout their interactions with a web application. Despite HTTP being a stateless protocol where the server treats each request independently, session management techniques ensure continuity by tracking user sessions. By leveraging these techniques, the server retains information about the client across multiple requests, facilitating personalized experiences and efficient data management. Thus, session management serves as a cornerstone for maintaining user sessions and enhancing the functionality of Node.js applications.

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 Exp: Whenever you are 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.

Steps to Setup the Project

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.

Example 1:

Implementation to show 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.

Project Structure :

The updated dependencies in package.json file will look like:

"dependencies": {
"cookie-parser": "^1.4.6",
"express": "^4.19.2",
"express-session": "^1.18.0",
"mongoose": "^8.4.0"
}

Example: Implementation to use session variable in nodejs.

JavaScript
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 the 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 is 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, the user stays in that session. When the user logs out, we will destroy the session.

Project Structure:

Example: Implementation to use session variable in nodejs.

JavaScript
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:



Previous Article
Next Article

Similar Reads

Session Management using express-session Module in Node.js
Session management can be done in node.js by using the express-session module. It helps in saving the data in the key-value form. In this module, the session data is not saved in the cookie itself, just the session ID. Installation of express-session module: You can visit the link Install express-session module. You can install this package by usin
2 min read
What is a session and how to start a session in PHP?
A session in PHP is a way to preserve data across subsequent HTTP requests. It allows information like user authentication status or user preferences to be stored and accessed throughout a user's interaction with a website. Starting a Session:To start a session in PHP, use the session_start() function at the beginning of your PHP script. This funct
2 min read
How to Clear Session Storage Data with Specified Session Storage Item?
JavaScript sessionStorage is a web storage technique that allows you to store data in a web browser. You can manually set and retrieve the values from it using some methods. The sessionStorage stores the data for a short amount of time until the browser tab or window gets closed. We will learn how to clear the session storage of a browser using Jav
2 min read
How to Expire Session After 1 Min of Inactivity in express-session of Express.js ?
To automatically expire sessions after 1 minute of inactivity in an Express.js application using express-session, configure the session settings with the cookie.maxAge and implement session touch logic to track activity. ApproachTo expire the session after 1 min of inactivity in the express-session of Express.js we use expires: 60000 in the middlew
2 min read
Node.js http2stream.session Method
The http2stream.session is an inbuilt application programming interface of class Http2Stream within http2 module which is used to get an reference to the Http2Session instance that owns this Http2Stream. Syntax: const http2stream.session Parameters: This method does not accept any parameter. Return Value: This method returns an reference to the Htt
3 min read
Session Cookies in Node.js
HTTP protocol: It is the backbone of the internet every single request from the client for particular contains several HTTP headers and that contains all the information of the request. This protocol is the foundation of the data exchange over the internet but the HTTP protocol is the stateless protocol means this protocol cannot be able to maintai
4 min read
React.js Blueprint Variables Font variables
In this article, we will learn about the Font Variables offered by the blueprint.js library. BlueprintJS is a React-based UI toolkit for the web. It is written in Typescript. This library is very optimized and popular for building interfaces that are complex and data-dense for desktop applications that run in a modern web browser. Font Variables: T
3 min read
Less.js Variables Default Variables
LESS (Leaner Style Sheets) is a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. It is a dynamic style sheet language that enhances the working power of CSS. LESS supports cross-browser compatibility. CSS pre-processor is a scripting language that improves CSS and gets compi
3 min read
Less.js Variables Properties as Variables
LESS (Leaner Style Sheets) is a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. It is a dynamic style sheet language that enhances the working power of CSS. LESS supports cross-browser compatibility. CSS pre-processor is a scripting language that improves CSS and gets compi
3 min read
PHP | Unset Session Variable
Whenever data are stored using cookies, there is a possibility of a hacker to insert some harmful data in the user's computer to harm any application. So its always advisable to use PHP sessions to store information on the server than on a computer. Whenever data is needed across many pages of a website or application, PHP Session is used. This ses
3 min read
ASP Session.Contents.RemoveAll Method
The Session.Contents.RemoveAll Method in ASP is used to remove or erase all the items from the content List. It is a predefined method of the Session type Object. Syntax: Session.Contents.RemoveAll() Parameter Value: This method does not contain any value. Return Value: It does not return any value. Example Code: Below code used to delete all the i
1 min read
ASP Session Timeout Property
The ASP Session.Timeout Property is used for setting or returning the amount of timeout interval for the session in the Application. The default timeout period is 20 minutes. The session will automatically end if the user does not refresh and not send any request for a page within a timeout period. Syntax Session.Timeout[=nMinutes] Property Value :
1 min read
ASP Session.Contents.Remove Method
The Session.Contents.Remove Method in ASP is used to remove an item from Session Contents collection. It is a predefined method of the Session type Object. Syntax Session.Contents.Remove(name|index) Parameter Values: It contains the value i.e name which represents the index of the specified items that would be removed from the Session. Example: Bel
1 min read
ASP Session.StaticObjects Collection
The Session.StaticObjects Collection in ASP is used to store all the objects created by using the <object> tag within the scope of the session object. Syntax: Session.StaticObjects( Key ) Parameter Values Key: It is a required parameter. It specifies the name of the property of an object that would be retrieved. Example: C/C++ Code <object
1 min read
ASP Session Abandon Method
The ASP Session.Abandon Method is used to destroy a session of the user. Generally , It destroys the object which are stored in the Session object. If we do not call the Abandon method explicitly, the server destroys these objects when the session times out. Note: When this method is called, the current Session object is not deleted until all the s
1 min read
ASP Session.SessionID Property
ASP Session.SessionID Property: It is a read-only property It means you can not modify this property. It returns a unique ID for each new user session that is generated by the user Every session gave a unique ID that is generated by the server when the session is created. It is stored as a cookie in the client machine. Syntax: Session.SessionID Exa
1 min read
ASP Session CodePage Property
The ASP Session CodePage Property is used to define a collection of characters that will be used to display the contents of a page in the Browser. Generally, the code page contains a character set that includes numbers, punctuation marks, and other glyphs. The CodePage property is read/write. This property is used to encoding a string in the intrin
1 min read
ASP Session LCID Property
The ASP Session LCID Property is used to set or get the locale identifier of a page that will be sent to the Browser. It sets or returns an integer that specifies the location or region contents like date, time, and currency of the region that will be displayed according to the location of a region. It is also known as local identifier Property. Sy
1 min read
ASP Session.Contents Collection
The ASP Session.Contents Collection is used for collecting the items which are appended to the Application object by using script command. This Collection can also be used to provide a list of items that have been given session scope, We can use the Contents.Remove and Contents.RemoveAll methods to remove some or all of the items from the collectio
1 min read
How to Destroy Session After Some Time in PHP ?
In PHP, we create sessions for the user who is logged in and make that user online till the user log out of that session. It can be done by clicking on the logout button or by destroying that session after a fixed time. By default the expiry time of any particular session that is created is 1440 secs i.e. (24*60) i.e. 24 minutes. But in some cases,
3 min read
How to set & unset session variable in codeigniter ?
The session class in CodeIgniter allows the user to maintain a user’s “state” and track their activity while browsing the website. The session can be initialized using the library and auto-loaded in the environment using the following command. $this->load->library('session'); Set the session variable: Session indexes can be assigned using key
2 min read
What are the difference between session and cookies in PHP ?
A session is a way to store information (in variables) to be used across multiple pages. When a user visits a website and starts a new session, the server creates a unique session ID and stores it in a cookie on the user's computer. The server also creates a file on the server to store the session variables for that user. The session ID in the cook
5 min read
How to store data in a PHP Session?
In PHP, sessions provide a way to persist data across multiple page requests for a single user. Storing data in a session allows developers to maintain user-specific information such as login status, user preferences, shopping cart items, etc. Syntax:// Start or resume a sessionsession_start();// Store data in the session$_SESSION['key'] = $value;I
2 min read
How to persist state with Local or Session Storage in React ?
Persisting state with localStorage or sessionStorage is a way to store data in the user's web browser so that it remains available even after the page is refreshed or closed. Persisting state with localStorage or sessionStorage: localStorage vs. sessionStorage:localStorage persists data until explicitly cleared by the user or the web application.se
2 min read
Managing Local Storage & Session Storage using React Hooks
To manage Loacal Storage and Session Storage, we can use hooks like useEffect and useState provided by React. Managing local or session storage is a repetitive task, so it is a good practice to create a custom hook that manages the storage properly. In this article, I'll cover the whole process of managing storage with the best industry standard pr
3 min read
How to Set Cookies Session per Visitor in JavaScript?
Managing session cookies in JavaScript is essential for web developers to maintain user state and preferences across multiple sessions. The document. cookie property provides a basic mechanism for cookie management, utilizing JavaScript libraries or frameworks can offer enhanced security and flexibility. Table of Content Using the document.cookie P
4 min read
What is express-session middleware in Express?
In the Express web application, the express-session middleware is mainly used for managing the sessions for the user-specific data. In this article, we will see the use of express-session middleware for session management in Express with practical implementation. PrerequisitesNode JSExpress JSTable of Content What is express-session Middleware?Step
2 min read
Web API Media Session
Web API Media Session is a powerful JavaScript feature that allows web developers to take control of media playback within their applications. By using it you can customize media notifications. It provides different actions by which you can control media playback and provide its metadata. Web API InterfacesIn the context of the Web API Media Sessio
3 min read
How to register a variable in PHP session ?
The PHP session is required so that you can store the user information and use it on different pages of the browser. Approach: It creates a session with the name or any other useful information you want to store and access on different pages. Even after your page is closed you can access the information until the browser does not close. This is an
3 min read
Difference Between Local Storage, Session Storage And Cookies
The HTTP protocol is one of the most important protocols for smooth communication between the server and the client. The main disadvantage of the HTTP protocol is that it is a stateless protocol, which means it does not track any kind of response or request by the server or the client. So to resolve this problem, we have Local Storage, Session Stor
6 min read
three90RightbarBannerImg