The Wayback Machine - https://web.archive.org/web/20240621123625/https://www.geeksforgeeks.org/session-management-using-express-session-module-in-node-js/
Open In App

Session Management using express-session Module in Node.js

Last Updated : 28 Apr, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. You can visit the link Install express-session module. You can install this package by using this command.
    npm install express-session
  2. After installing express-session you can check your express-session version in command prompt using the command.
    npm version express-session
  3. After that, you can create a folder and add a file for example index.js, To run this file you need to run the following command.
    node index.js

Filename: index.js




const express = require("express")
const session = require('express-session')
const app = express()
    
// Port Number Setup
var PORT = process.env.port || 3000
   
// Session Setup
app.use(session({
  
    // It holds the secret key for session
    secret: 'Your_Secret_Key',
  
    // Forces the session to be saved
    // back to the session store
    resave: true,
  
    // Forces a session that is "uninitialized"
    // to be saved to the store
    saveUninitialized: true
}))
   
app.get("/", function(req, res){
       
    // req.session.key = value
    req.session.name = 'GeeksforGeeks'
    return res.send("Session Set")
})
   
app.get("/session", function(req, res){
   
    var name = req.session.name
    return res.send(name)
   
    /*  To destroy session you can use
        this function 
     req.session.destroy(function(error){
        console.log("Session Destroyed")
    })
    */
})
    
app.listen(PORT, function(error){
    if(error) throw error
    console.log("Server created Successfully on PORT :", PORT)
})


Steps to run the program:

  1. The project structure will look like this:
    project structure
  2. Make sure you have install express and express-session module using following commands:
    npm install express
    npm install express-session
  3. Run index.js file using below command:
    node index.js

    Output of above command

  4. Now to set your session, just open browser and type this URL:
    http://localhost:3000/

  5. Till now, you have set session and to see session value, type this URL:
    http://localhost:3000/session

So this is how you can do session management in node.js using the express-session module.



Similar Reads

How to expire session after 1 min of inactivity in express-session of Express.js ?
In this article, we will see how to expire the session after 1 min of inactivity in express-session of Express.js. Prerequisites Installation of Node.js on WindowsTo set up Node Project in Editor see here. Requires Modules: npm install express npm install express-session Call API: var session = require('express-session') To expire the session after
2 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
What are the differences between HTTP module and Express.js module ?
HTTP and Express both are used in NodeJS for development. In this article, we'll go through HTTP and express modules separately HTTP: It is an in-build module which is pre-installed along with NodeJS. It is used to create server and set up connections. Using this connection, data sending and receiving can be done as long as connections use a hypert
2 min read
How to clear session storage data with specified session storage item ?
In this article, we are going to learn how we can clear the session storage of a browser using JavaScript by getting the specified session storage item. We can achieve this by using Window sessionStorage( ) property. The Window sessionStorage() property is used for saving key/value pairs in a web browser. It stores the key/value pairs in a browser
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 Validate Data using express-validator Module in Node.js ?
Validation in node.js can be easily done by using the express-validator module. This module is popular for data validation. There are other modules available in market like hapi/joi, etc but express-validator is widely used and popular among them.Steps to install express-validator module: You can install this package by using this command. npm inst
3 min read
How to export promises from one module to another module node.js ?
JavaScript is an asynchronous single-threaded programming language. Asynchronous means multiple processes are handled at the same time. Callback functions vary for the asynchronous nature of the JavaScript language. A callback is a function that is called when a task is completed, thus helps in preventing any kind of blocking and a callback functio
1 min read
Task Management System using Node and Express.js
Task Management System is one of the most important tools when you want to organize your tasks. NodeJS and ExpressJS are used in this article to create a REST API for performing all CRUD operations on task. It has two models User and Task. ReactJS and Tailwind CSS are used to create a frontend interface part in which we can add, delete, and update
15+ min read
Customer Relationship Management (CRM) System with Node.js and Express.js
CRM systems are important tools for businesses to manage their customer interactions, both with existing and potential clients. In this article, we will demonstrate how to create a CRM system using Node.js and Express. We will cover the key functionalities, prerequisites, approach, and steps required to create the project. Output Preview: Prerequis
15+ min read
How to allow classes defined in a module that can be accessible outside of the module ?
The TypeScript scripts written by default are in the global scope which means that all the functions, methods, variables, etc. in one file are accessible in all other TypeScript files. This can lead to conflicts in variables, functions as programmers can edit the function/variable name or value without any realization. Therefore, the concept of mod
3 min read