Open In App

How to Manage Sessions and Cookies in Express JS?

Last Updated : 23 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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-structure-managing-sessions
Project Structure

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




Next Article

Similar Reads