How to Manage Sessions and Cookies in Express JS?
Last Updated :
23 Jul, 2024
Express is a small framework that sits on top of NodeJS web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your application’s functionality with middleware and routing. It adds helpful utilities to NodeJS HTTP objects, it helps the rendering of dynamic HTTP objects. Express is a part of MEAN stack, a full-stack JavaScript solution for building fast, robust, and maintainable production web applications.
In this post, we will learn how to manage sessions and cookies in Express JS. Two packages in Express js are commonly used to manage cookies and sessions in Express JS. These are the package examples 'express-session' and for cookie parsing 'cookie-parser.'
Approach
To manage sessions and cookies in Express.js, use express-session to store session data and cookie-parser to parse cookies. Implement middleware to protect routes and use session data to maintain user state across requests.
Sessions in Express JS
A session is a way to persist user-specific data across multiple requests in web applications. In express provides the 'express-session' middleware to manage the session. The below command demonstrates the 'How to install the express-session' module in express using the npm.
npm install express express-session
Now, we have express-session in our express js application. Below are programs on how we can use this express-session middleware in our express js application.
const express = require("express");
const session = require("express-session");
const app = express();
app.use(
session({
secret: "your-secret-key",
resave: false,
saveUninitialized: false,
})
);
Parameters:
- secret: It is a key that is used to sign a session ID cookie. It must be a strong and unique secret.
- resave Forces the session to be saved back to the session store, even if the session wasn't modified.
- saveUninitialized: Forces a session that is "uninitialized" to be saved to the store. A session is uninitialized when it is new but not modified.
Cookies in Express JS
It is the small pieces of data that are stored in the client's browser. Express has a middleware 'cookie-parser' that is issued to set cookies. The following command installs that middleware in your application.
npm install cookie-parser
Updated dependencies in the package.json file:
"dependencies": {
"cookie-parser": "^1.4.6",
"express": "^4.19.2",
"express-session": "^1.18.0"
}
Include the cookie-parser middleware function in your express js program.
const cookieParser = require('cookie-parser');
app.use(cookieParser());
Project Structure:
Project StructureExample: The following program demonstrates 'express-session' and 'cookie-parser' usage in Expres JS
HTML
<!-- login.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
form {
width: 300px;
padding: 20px;
border: 1px solid #ccc;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
label {
display: block;
margin-bottom: 8px;
}
input {
width: 100%;
padding: 8px;
margin-bottom: 16px;
box-sizing: border-box;
}
button {
background-color: #4caf50;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<form action="/login" method="post">
<h2>Login</h2>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br>
<button type="submit">Login</button>
</form>
</body>
</html>
JavaScript
// index.js
const express = require("express");
const session = require("express-session");
const cookieParser = require("cookie-parser");
const app = express();
// Middleware setup
app.use(
session({
secret: "your-secret-key",
resave: false,
saveUninitialized: false,
})
);
app.use(cookieParser());
// Sample user data for demonstration purposes
// Middleware to check if the user is authenticated
const isAuthenticated = (req, res, next) => {
if (req.session.user) {
next();
} else {
res.redirect("/login");
}
};
// Routes
app.get("/", (req, res) => {
res.send("Welcome to the Express.js Session and Cookies Example!");
});
app.get("/login", (req, res) => {
res.sendFile(__dirname + "/login.html");
});
app.post("/login", express.urlencoded({ extended: true }), (req, res) => {
const { username, password } = req.body;
// Check if the provided credentials are valid
if (username === "admin" && password === "admin") {
// Store user data in the session
req.session.user = username;
res.cookie("sessionId", req.sessionID);
res.redirect("/profile");
} else {
res.send("Invalid credentials. Please try again.");
}
});
app.get("/profile", isAuthenticated, (req, res) => {
// Retrieve user data from the session
const username = req.session.user;
res.send(`Welcome, ${username}!
<a href="/logout">Logout</a>`);
});
app.get("/logout", (req, res) => {
// Destroy the session and redirect to the login page
req.session.destroy(() => {
res.clearCookie("sessionId");
res.redirect("/login");
});
});
// Start the server
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Output:
Similar Reads
How to manipulate cookies by using âResponse.cookie()â in Express?
Cookies are small data that is stored on the client's computer. Using this cookie various tasks like authentication, session management, etc can be done. In Express JS we can use the cookie-parser middleware to manage the cookies in the application. In this article, we going to manipulate cookies in
3 min read
How to Exit after res.send() in Express JS
In this article, we are going to learn how we can exit after the res.send() function in Express JS. In Express the res.send() method is mainly used to send a response to the client with the specified content. This function automatically sets the Content-Type Header which is based on the data provide
3 min read
How to preserve cookies or localStorage session across tests in Cypress
When creating end-to-end tests using Cypress, a common obstacle is finding a way to retain cookies or localStorage session information across multiple tests. This is because Cypress, by design, clears all cookies and localStorage data between tests to maintain isolation and prevent test interference
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 prot
4 min read
How to use Template Engines in Express JS ?
Express.js is a popular web framework for Node.js that simplifies the process of building web applications. One of the key features of Express is its ability to integrate with template engines, allowing developers to dynamically generate HTML pages with data from their server. In this article, we'll
3 min read
How to handle sessions in Express ?
ExpressJS is a small framework that works on top of Node web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your applicationâs functionality with middleware and routing. It adds helpful utilities to Node HTTP objects and facilitates the render
4 min read
Difference between sessions and cookies in Express
Express.js is a popular framework for Node.js, that is used to create web applications. It provides tools to manage user sessions and cookies. The session and cookies are used to maintain the state and manage user authentication. In this article, we will learn about what sessions and cookies in Expr
3 min read
How to do Templating using ExpressJS in Node.js ?
Template Engine : A template engine basically helps us to use the static template files with minimal code. At runtime, the template engine replaces all the variables with actual values at the client-side. Templating Engine Examples: EJS (Embedded JavaScript Templating) Pug Mustache In this article w
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
2 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 flexibi
4 min read