Introduction
Cookies and sessions are important concepts for managing users in Node.js web applications. Cookies store small pieces of information in the user’s browser, while sessions help a server remember a user’s login state across multiple requests. In this chapter, you will practice cookies and sessions step by step, starting with creating cookies and reading them, then moving to login sessions, protected routes, and session-based authentication. Node.js Cookies and Sessions practice questions with solutions help to understand the concepts.
Question 1: How do you create a basic cookie in Node.js?
Problem
Create a simple Node.js server that sends a cookie to the browser.
Solution
First, create a Node.js project:
npm init -y
Install Express:
npm install express
Create index.js:
const express = require("express");
const app = express();
app.get("/", (req, res) => {
res.setHeader(
"Set-Cookie",
"username=rahul"
);
res.send(
"Cookie has been created."
);
});
app.listen(3000, () => {
console.log(
"Server running on port 3000"
);
});
Step-by-Step Explanation
The important line is:
res.setHeader(
"Set-Cookie",
"username=rahul"
);
The server sends a Set-Cookie response header to the browser.
The browser can then store:
username=rahul
Output
Open:
http://localhost:3000
You will see:
Cookie has been created.
The browser now has a cookie named username.
Important Point
Cookies are stored by the browser and are automatically sent back to the server according to the cookie’s rules.
Question 2: How do you create a cookie with an expiration time?
Problem
Create a cookie that expires after one hour.
Solution
const express = require("express");
const app = express();
app.get("/set-cookie", (req, res) => {
res.setHeader(
"Set-Cookie",
"username=rahul; Max-Age=3600"
);
res.send(
"Cookie created for one hour."
);
});
app.listen(3000, () => {
console.log(
"Server running on port 3000"
);
});
Step-by-Step Explanation
The cookie is:
username=rahul
The following option controls how long it can remain:
Max-Age=3600
3600 seconds equals one hour.
3600 seconds
÷ 60
= 60 minutes
Therefore:
3600 seconds = 1 hour
Example
res.setHeader(
"Set-Cookie",
"username=rahul; Max-Age=3600"
);
Important Point
Cookie lifetime and session lifetime are related concepts but are not the same thing. A cookie can persist for a specified period, while a server-side session has its own expiration and storage rules.
Question 3: How do you read cookies in Node.js?
Problem
Create a Node.js server that reads a cookie sent by the browser.
Solution
const express = require("express");
const app = express();
app.get("/profile", (req, res) => {
const cookie =
req.headers.cookie;
console.log(
"Cookies:",
cookie
);
res.send(
"Cookie received."
);
});
app.listen(3000, () => {
console.log(
"Server running on port 3000"
);
});
Step-by-Step Explanation
The browser sends cookies using the Cookie request header.
Node.js can read this header using:
req.headers.cookie
For example, the browser might send:
Cookie: username=rahul
Node.js receives:
username=rahul
Important Point
req.headers.cookie gives you the raw cookie header. If your application has multiple cookies, you usually need a cookie parser or parsing logic to work with individual cookie values conveniently.
Question 4: How do you use the cookie-parser package?
Problem
Use the cookie-parser package to easily create and read cookies in Express.js.
Solution
Install the package:
npm install express cookie-parser
Create index.js:
const express = require("express");
const cookieParser =
require("cookie-parser");
const app = express();
app.use(cookieParser());
// Create cookie
app.get("/login", (req, res) => {
res.cookie(
"username",
"rahul"
);
res.send(
"Cookie created."
);
});
// Read cookie
app.get("/profile", (req, res) => {
const username =
req.cookies.username;
res.send(
`Welcome ${username}`
);
});
app.listen(3000, () => {
console.log(
"Server running on port 3000"
);
});
Step-by-Step Explanation
First import the package:
const cookieParser =
require("cookie-parser");
Enable it:
app.use(cookieParser());
Create a cookie:
res.cookie(
"username",
"rahul"
);
Read the cookie:
req.cookies.username
Test
Open:
http://localhost:3000/login
Then open:
http://localhost:3000/profile
You should see:
Welcome rahul
Important Point
cookie-parser makes cookie handling much easier than manually processing the raw Cookie header.
Question 5: How do you delete a cookie?
Problem
Create an Express.js application that creates a cookie and then deletes it.
Solution
const express = require("express");
const cookieParser =
require("cookie-parser");
const app = express();
app.use(cookieParser());
// Create cookie
app.get("/set-cookie", (req, res) => {
res.cookie(
"username",
"rahul"
);
res.send(
"Cookie created."
);
});
// Delete cookie
app.get("/delete-cookie", (req, res) => {
res.clearCookie(
"username"
);
res.send(
"Cookie deleted."
);
});
app.listen(3000, () => {
console.log(
"Server running on port 3000"
);
});
Step-by-Step Explanation
Create the cookie:
res.cookie(
"username",
"rahul"
);
Delete it:
res.clearCookie(
"username"
);
Test
First visit:
http://localhost:3000/set-cookie
Then visit:
http://localhost:3000/delete-cookie
The username cookie will be cleared.
Question 6: How do you create a basic session in Express.js?
Problem
Create a session that stores a user’s username after visiting a login route.
Solution
Install the required packages:
npm install express express-session
Create index.js:
const express = require("express");
const session =
require("express-session");
const app = express();
app.use(
session({
secret:
"my-session-secret",
resave: false,
saveUninitialized: false
})
);
// Login
app.get("/login", (req, res) => {
req.session.username =
"rahul";
res.send(
"Login successful."
);
});
// Profile
app.get("/profile", (req, res) => {
const username =
req.session.username;
if (!username) {
return res.status(401).send(
"Please login first."
);
}
res.send(
`Welcome ${username}`
);
});
app.listen(3000, () => {
console.log(
"Server running on port 3000"
);
});
Step-by-Step Explanation
First import the package:
const session =
require("express-session");
Enable sessions:
app.use(
session({
secret:
"my-session-secret",
resave: false,
saveUninitialized: false
})
);
Store information:
req.session.username =
"rahul";
Read the information:
req.session.username
Test
Open:
http://localhost:3000/login
Then open:
http://localhost:3000/profile
You should see:
Welcome rahul
Important Point
The session data is maintained on the server side when using the default session store, while the browser typically receives a session identifier cookie.
Question 7: How do you create login and logout using sessions?
Problem
Build a simple session-based login system with:
- Login
- Profile
- Logout
Solution
const express = require("express");
const session =
require("express-session");
const app = express();
app.use(express.urlencoded({
extended: true
}));
app.use(
session({
secret:
"my-session-secret",
resave: false,
saveUninitialized: false
})
);
// Login
app.post("/login", (req, res) => {
const username =
req.body.username;
const password =
req.body.password;
if (
username === "rahul" &&
password === "12345"
) {
req.session.username =
username;
return res.send(
"Login successful."
);
}
res.status(401).send(
"Invalid username or password."
);
});
// Profile
app.get("/profile", (req, res) => {
if (!req.session.username) {
return res.status(401).send(
"Please login first."
);
}
res.send(
`Welcome ${req.session.username}`
);
});
// Logout
app.get("/logout", (req, res) => {
req.session.destroy((error) => {
if (error) {
return res.status(500).send(
"Logout failed."
);
}
res.send(
"Logout successful."
);
});
});
app.listen(3000, () => {
console.log(
"Server running on port 3000"
);
});
Test Login
Send a POST request to:
/login
with:
username=rahul
password=12345
After successful login:
req.session.username =
username;
stores the username in the session.
Test Profile
Open:
/profile
You will see:
Welcome rahul
Test Logout
Open:
/logout
The session is destroyed.
After logout, visiting:
/profile
will return:
Please login first.
Important Point
req.session.destroy() removes the session from the session store and ends that session.
Question 8: How do you protect a route using session middleware?
Problem
Create reusable middleware that allows only logged-in users to access a protected route.
Solution
const express = require("express");
const session =
require("express-session");
const app = express();
app.use(
session({
secret:
"my-session-secret",
resave: false,
saveUninitialized: false
})
);
// Authentication middleware
function requireLogin(
req,
res,
next
) {
if (!req.session.username) {
return res.status(401).send(
"You must login first."
);
}
next();
}
// Login route
app.get("/login", (req, res) => {
req.session.username =
"rahul";
res.send(
"Login successful."
);
});
// Public route
app.get("/home", (req, res) => {
res.send(
"This is a public page."
);
});
// Protected route
app.get(
"/dashboard",
requireLogin,
(req, res) => {
res.send(
`Welcome to your dashboard, ${req.session.username}`
);
}
);
app.listen(3000, () => {
console.log(
"Server running on port 3000"
);
});
Step-by-Step Explanation
The middleware checks:
if (!req.session.username)
If the user is not logged in:
return res.status(401).send(
"You must login first."
);
If the user is logged in:
next();
The request continues to the dashboard.
Protected Route
app.get(
"/dashboard",
requireLogin,
(req, res) => {
res.send(
`Welcome to your dashboard, ${req.session.username}`
);
}
);
Important Point
Middleware allows you to write authentication logic once and reuse it across many protected routes.
Question 9: How do you configure secure session cookies?
Problem
Configure an Express session cookie using common security-related options.
Solution
const express = require("express");
const session =
require("express-session");
const app = express();
app.set(
"trust proxy",
1
);
app.use(
session({
secret:
process.env.SESSION_SECRET ||
"development-secret",
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: true,
sameSite: "lax",
maxAge:
1000 * 60 * 60
}
})
);
app.get("/", (req, res) => {
res.send(
"Secure session configuration example."
);
});
app.listen(3000, () => {
console.log(
"Server running on port 3000"
);
});
Understanding the Options
httpOnly
httpOnly: true
This prevents normal client-side JavaScript from reading the cookie.
It helps reduce the impact of certain types of cross-site scripting attacks.
secure
secure: true
The browser should send the cookie only over HTTPS.
For local HTTP development, you may need:
secure: false
or conditional configuration.
sameSite
sameSite: "lax"
This controls when browsers send the cookie in cross-site situations.
maxAge
maxAge:
1000 * 60 * 60
This represents one hour in milliseconds.
Important Point
Cookie security settings should be selected according to the application’s deployment environment and authentication design.
Question 10: How do you build a complete session-based login system?
Problem
Create a beginner-friendly Express.js application with:
- Registration-style user data
- Login
- Session creation
- Protected dashboard
- Logout
- Session-based authentication
Solution
const express = require("express");
const session =
require("express-session");
const app = express();
app.use(express.json());
app.use(
session({
secret:
process.env.SESSION_SECRET ||
"development-secret",
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
sameSite: "lax",
maxAge:
1000 * 60 * 60
}
})
);
// Demo user
const user = {
username:
"rahul",
password:
"12345"
};
// Login
app.post(
"/login",
(req, res) => {
const {
username,
password
} = req.body;
if (
username !== user.username ||
password !== user.password
) {
return res.status(401).json({
success: false,
message:
"Invalid username or password."
});
}
req.session.user = {
username:
user.username
};
res.json({
success: true,
message:
"Login successful."
});
}
);
// Authentication middleware
function requireLogin(
req,
res,
next
) {
if (!req.session.user) {
return res.status(401).json({
success: false,
message:
"Please login first."
});
}
next();
}
// Protected dashboard
app.get(
"/dashboard",
requireLogin,
(req, res) => {
res.json({
success: true,
message:
"Welcome to the dashboard.",
user:
req.session.user
});
}
);
// Logout
app.post(
"/logout",
(req, res) => {
req.session.destroy(
(error) => {
if (error) {
return res.status(500).json({
success: false,
message:
"Logout failed."
});
}
res.json({
success: true,
message:
"Logout successful."
});
}
);
}
);
app.listen(3000, () => {
console.log(
"Server running on port 3000"
);
});
Step-by-Step Flow
USER
|
↓
LOGIN
|
↓
Check Username/Password
|
┌─────┴─────┐
↓ ↓
Valid Invalid
↓ ↓
Create Session 401 Error
|
↓
Session Cookie
|
↓
Protected Route
|
↓
Check Session
|
┌───┴───┐
↓ ↓
Valid Missing
↓ ↓
Dashboard 401 Error
|
↓
Logout
|
↓
Destroy Session
Test Login
Send:
POST http://localhost:3000/login
JSON:
{
"username": "rahul",
"password": "12345"
}
Response:
{
"success": true,
"message": "Login successful."
}
The server creates a session:
req.session.user = {
username:
user.username
};
Test Dashboard
Send:
GET http://localhost:3000/dashboard
If the session is valid:
{
"success": true,
"message": "Welcome to the dashboard.",
"user": {
"username": "rahul"
}
}
Test Logout
Send:
POST http://localhost:3000/logout
The session is destroyed:
req.session.destroy(
(error) => {
...
}
);
After logout, trying to access:
/dashboard
will return an authentication error.
Important Point
The example uses a hard-coded user only for learning. A real application should store users in a database, hash passwords, validate input, use a strong session secret, and use an appropriate production session store instead of relying on the default in-memory session store.
Key Takeaways
1. Cookies are stored by the browser
A cookie is a small piece of data that a website can ask the browser to store.
2. Sessions help maintain user state
HTTP requests are normally independent. Sessions allow an application to remember information about a user between requests.
3. res.cookie() creates cookies
With cookie-parser installed, Express can create cookies using:
res.cookie(
"username",
"rahul"
);
4. req.cookies reads cookies
After enabling cookie-parser:
app.use(cookieParser());
you can read:
req.cookies.username
5. res.clearCookie() removes cookies
Example:
res.clearCookie(
"username"
);
6. express-session provides session management
Install it with:
npm install express-session
Then configure it with:
app.use(
session({
secret: "my-secret"
})
);
7. Session information can be stored in req.session
For example:
req.session.username =
"rahul";
8. Sessions commonly use a session ID cookie
The browser generally stores a session identifier, while the server-side session store holds the associated session data.
9. Middleware can protect routes
A middleware function can check whether a session exists before allowing access to a protected route.
10. req.session.destroy() logs a user out
Example:
req.session.destroy(
(error) => {
...
}
);
11. httpOnly improves cookie security
An httpOnly cookie cannot normally be accessed through browser JavaScript.
12. secure restricts cookies to HTTPS
Use:
secure: true
when the application is correctly deployed over HTTPS.
13. sameSite controls cross-site cookie behavior
Common values include:
strict
lax
none
14. Never store passwords directly in cookies
Passwords should never be placed inside ordinary cookies.
15. Do not store sensitive information casually in cookies
Cookie contents may be available to the browser and are sent with applicable requests.
16. Cookies and sessions are not the same
A cookie is client-side browser data.
A session is an application-level mechanism for maintaining state, commonly associated with a session ID cookie.
17. Use a production session store
The default in-memory session store is intended for development and debugging, not production applications.
18. Use environment variables for secrets
Instead of:
secret: "my-secret"
use an environment variable:
secret:
process.env.SESSION_SECRET
19. Session authentication and JWT authentication are different approaches
Session authentication generally keeps session state on the server.
JWT authentication commonly uses a signed token that the server verifies on requests.
20. Authentication and authorization are different
Authentication answers:
Who are you?
Authorization answers:
What are you allowed to access?
FAQs
1. What is a cookie in Node.js?
A cookie is a small piece of data stored by the user’s browser. Websites can use cookies to remember information such as preferences, identifiers, or session IDs.
Node.js applications can create cookies using response headers or libraries such as cookie-parser.
2. What is a session in Node.js?
A session allows a server-side application to remember information about a user across multiple HTTP requests.
For example:
req.session.username =
"rahul";
The application can later read:
req.session.username
3. What is the difference between cookies and sessions?
The basic difference is where the main information is maintained.
Cookie
↓
Stored by the browser
Session
↓
Usually stored on the server
With Express sessions, the browser commonly receives a session ID cookie that allows the server to identify the associated session.
4. How do I create cookies in Express.js?
Install cookie-parser:
npm install cookie-parser
Then:
const cookieParser =
require("cookie-parser");
app.use(cookieParser());
app.get("/", (req, res) => {
res.cookie(
"username",
"rahul"
);
res.send(
"Cookie created."
);
});
5. How do I create a session in Express.js?
Install express-session:
npm install express-session
Then configure it:
const session =
require("express-session");
app.use(
session({
secret:
"my-secret",
resave: false,
saveUninitialized: false
})
);
You can then store data using:
req.session.username =
"rahul";
6. How do I log out a user from an Express session?
Use req.session.destroy():
app.post("/logout", (req, res) => {
req.session.destroy(
(error) => {
if (error) {
return res.status(500).send(
"Logout failed."
);
}
res.send(
"Logout successful."
);
}
);
});
This destroys the current session.
7. Are cookies and sessions secure?
They can be used securely when configured correctly, but neither is automatically secure.
For production applications, use HTTPS, appropriate cookie settings such as httpOnly, secure, and sameSite, strong secrets, proper session storage, password hashing, input validation, and appropriate authentication and authorization controls.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
