Introduction
When building a web application, we often need to remember information about a user between multiple requests.
For example:
-
Is the user logged in?
-
Which user is currently logged in?
-
What is in the user's shopping cart?
-
What preferences has the user selected?
-
Has the user completed a particular step?
HTTP is stateless by default.
This means the server doesn't automatically remember previous requests.
For example:
Request 1
GET /login
Request 2
GET /profile
Request 3
GET /orders
By default, these are treated as separate requests.
This is where sessions come in.
In this article, we'll learn:
-
What a session is
-
How sessions work
-
What
express-sessionis -
How to install and configure it
-
How to create session data
-
How to read and update session data
-
How to destroy a session
-
Important
express-sessionproperties -
Session cookies
-
Session security
-
A simple login/logout example
What Is a Session?
A session is a way for a server to maintain state for a user across multiple HTTP requests.
A simple session flow looks like this:
User logs in
↓
Server creates a session
↓
Session gets an ID
↓
Session ID is sent to browser
↓
Browser sends session ID
with future requests
↓
Server finds the session
↓
Server knows the user
For example, the server might maintain session data like:
{
userId: 101,
isLoggedIn: true
}
The browser doesn't normally store this entire object as the session cookie. Instead, it stores a session identifier that allows the server to find the associated session.
Why Do We Need Sessions?
Imagine a user logs in:
POST /login
The server validates the username and password.
Then the user visits:
GET /profile
How does the server know which user is requesting /profile?
A session can solve this problem.
The server can create a session containing:
{
userId: 101
}
The browser receives a session identifier.
On subsequent requests, the browser sends that identifier back.
The server uses it to find the corresponding session.
What Is express-session?
express-session is middleware for Express.js that provides session management.
It allows you to store data associated with a user's session and access that data across different requests.
Install it using:
npm install express-session
Creating a Basic Express Session
Let's create a simple Express application.
const express = require("express");
const session = require("express-session");
const app = express();
app.use(
session({
secret: "my-secret-key",
resave: false,
saveUninitialized: false
})
);
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Now our Express application has session support.
Understanding Session Configuration
The basic configuration is:
session({
secret: "my-secret-key",
resave: false,
saveUninitialized: false
});
There are several important properties here.
Let's understand them one by one.
1. secret
The secret property is used to sign the session ID cookie.
session({
secret: "my-secret-key"
});
In a real application, don't hard-code the secret.
Instead, use an environment variable:
SESSION_SECRET=your-long-random-secret
Then:
session({
secret: process.env.SESSION_SECRET
});
The secret should be kept private and should never be committed to GitHub.
2. resave
The resave property determines whether the session should be saved back to the session store even when it wasn't modified during the request.
For example:
session({
secret: process.env.SESSION_SECRET,
resave: false
});
In most applications:
resave: false
is a good starting point.
It avoids unnecessarily saving unchanged sessions.
3. saveUninitialized
The saveUninitialized property determines whether a session that hasn't been modified should be saved.
For example:
session({
secret: process.env.SESSION_SECRET,
saveUninitialized: false
});
Using:
saveUninitialized: false
is commonly useful because it avoids creating and storing sessions that haven't actually been used.
Creating Session Data
Once express-session is configured, you can access the session using:
req.session
For example:
app.get("/login", (req, res) => {
req.session.userId = 101;
res.send("User logged in");
});
Now the session contains:
{
userId: 101
}
Reading Session Data
You can access session data through:
req.session
For example:
app.get("/profile", (req, res) => {
const userId = req.session.userId;
res.json({
userId
});
});
If the session contains:
userId = 101
the response will be:
{
"userId": 101
}
Updating Session Data
You can modify session properties just like normal JavaScript object properties.
app.get("/update-user", (req, res) => {
req.session.userId = 200;
req.session.role = "admin";
res.json({
message: "Session updated"
});
});
The session now contains:
{
userId: 200,
role: "admin"
}
Storing Multiple Values
You can store multiple values in a session:
req.session.user = {
id: 101,
name: "John",
role: "user"
};
Then access them:
const user = req.session.user;
console.log(user.id);
console.log(user.name);
console.log(user.role);
However, avoid storing unnecessarily large objects in a session.
A common approach is to store only the information needed to identify the user:
req.session.userId = user.id;
Checking Whether a User Is Logged In
A simple authentication check could be:
app.get("/profile", (req, res) => {
if (!req.session.userId) {
return res.status(401).json({
message: "Please login first"
});
}
res.json({
message: "Welcome to your profile",
userId: req.session.userId
});
});
If userId doesn't exist, the user isn't considered authenticated in this example.
Destroying a Session
When the user logs out, you usually want to destroy the session.
Use:
req.session.destroy()
For example:
app.get("/logout", (req, res) => {
req.session.destroy((err) => {
if (err) {
return res.status(500).json({
message: "Unable to logout"
});
}
res.json({
message: "Logged out successfully"
});
});
});
After the session is destroyed, the server no longer has that session data.
req.session.destroy()
The destroy() method destroys the current session.
req.session.destroy((err) => {
if (err) {
console.error(err);
return;
}
console.log("Session destroyed");
});
This is commonly used during logout.
Session Cookie
When you use express-session, the browser receives a cookie containing the session identifier.
For example:
connect.sid=some-session-id
The cookie normally does not contain the entire session data.
Instead:
Browser
|
| Session Cookie
v
Express Server
|
| Session ID
v
Session Store
|
v
Session Data
This is an important concept when working with sessions.
The cookie Property
You can configure the session cookie using the cookie property.
For example:
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 60 * 60 * 1000
}
})
);
Here:
60 * 60 * 1000 = 1 hour
So the cookie can remain valid for one hour.
Important Cookie Properties
Some commonly used cookie properties are:
cookie: {
maxAge: 60 * 60 * 1000,
httpOnly: true,
secure: true,
sameSite: "lax"
}
Let's understand them.
maxAge
Defines how long the session cookie remains valid.
cookie: {
maxAge: 60 * 60 * 1000
}
The value is in milliseconds.
For example:
1000 milliseconds = 1 second
60 * 60 * 1000 = 1 hour
httpOnly
cookie: {
httpOnly: true
}
This prevents client-side JavaScript from directly accessing the cookie through:
document.cookie
This is commonly enabled for authentication/session cookies.
secure
cookie: {
secure: true
}
This tells the browser to send the cookie only over HTTPS.
In production, when your application uses HTTPS, this is generally an important security setting.
During local development over plain HTTP, you may need to use:
secure: false
sameSite
cookie: {
sameSite: "lax"
}
This controls when the browser sends the cookie in cross-site requests.
Common values are:
strict
lax
none
The appropriate setting depends on your application's frontend and backend architecture.
Session Properties vs Cookie Properties
This can sometimes be confusing.
The main session configuration contains:
session({
secret,
resave,
saveUninitialized,
cookie
});
The cookie object contains browser cookie settings:
cookie: {
maxAge,
httpOnly,
secure,
sameSite
}
Think of it like this:
session()
|
├── secret
├── resave
├── saveUninitialized
|
└── cookie
|
├── maxAge
├── httpOnly
├── secure
└── sameSite
Accessing the Session ID
You can access the current session ID using:
req.sessionID
For example:
app.get("/session", (req, res) => {
res.json({
sessionId: req.sessionID
});
});
You generally shouldn't expose session IDs unnecessarily.
Regenerating a Session
express-session provides:
req.session.regenerate()
This creates a new session.
A common use case is after a successful login.
app.post("/login", (req, res) => {
// Validate username and password first
req.session.regenerate((err) => {
if (err) {
return res.status(500).json({
message: "Unable to create session"
});
}
req.session.userId = 101;
res.json({
message: "Login successful"
});
});
});
Regenerating the session after authentication can help protect against session fixation attacks.
Complete Login and Logout Example
Let's put everything together.
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,
secure: false,
sameSite: "lax",
maxAge: 60 * 60 * 1000
}
})
);
// Login
app.post("/login", (req, res) => {
const { username, password } = req.body;
// Example only.
// In a real application, validate against a database.
if (username !== "john" || password !== "123456") {
return res.status(401).json({
message: "Invalid username or password"
});
}
req.session.regenerate((err) => {
if (err) {
return res.status(500).json({
message: "Unable to create session"
});
}
req.session.userId = 101;
req.session.username = username;
res.json({
message: "Login successful"
});
});
});
// Profile
app.get("/profile", (req, res) => {
if (!req.session.userId) {
return res.status(401).json({
message: "Please login first"
});
}
res.json({
userId: req.session.userId,
username: req.session.username
});
});
// Logout
app.post("/logout", (req, res) => {
req.session.destroy((err) => {
if (err) {
return res.status(500).json({
message: "Logout failed"
});
}
res.json({
message: "Logout successful"
});
});
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
How This Login Flow Works
The flow is:
POST /login
|
v
Validate username/password
|
v
Create/regenerate session
|
v
Store userId in session
|
v
Browser receives session cookie
|
v
GET /profile
|
v
Browser sends session cookie
|
v
Express finds the session
|
v
Read req.session.userId
|
v
Return profile
Logout works like this:
POST /logout
|
v
req.session.destroy()
|
v
Session removed
|
v
User logged out
Default Session Store
By default, express-session uses an in-memory session store.
This is useful for development and learning.
However, you should not use the default memory store in production.
For example, if your application has multiple server instances:
Load Balancer
|
+-------+-------+
| |
v v
Server 1 Server 2
A session stored only in Server 1's memory isn't automatically available to Server 2.
For production applications, use a proper shared session store such as Redis or another compatible session store.
Sessions vs Cookies
Sessions and cookies are related, but they aren't the same thing.
A cookie is data stored by the browser.
A session is server-side state associated with a session identifier.
A simplified example:
Browser
|
| connect.sid=ABC123
v
Server
|
| Session ID = ABC123
v
Session Store
|
v
{
userId: 101
}
The browser typically stores the session identifier, while the session data is maintained by the server-side session store.
Sessions vs JWT
Sessions aren't the only way to implement authentication.
Another popular approach is JWT-based authentication.
Session-based authentication
Browser
|
| Session Cookie
v
Server
|
v
Session Store
JWT-based authentication
Browser
|
| JWT
v
Server
|
v
Verify JWT
Both approaches have advantages and trade-offs.
For traditional server-rendered applications, sessions are very common.
For APIs and distributed applications, JWTs can sometimes be a better fit.
The right choice depends on your application's architecture and requirements.
Session Security Best Practices
When using sessions for authentication, security is important.
1. Use a Strong Secret
Avoid:
secret: "123456"
Instead:
secret: process.env.SESSION_SECRET
Use a long, random secret and keep it private.
2. Use HTTPS
Authentication/session cookies should generally be transmitted over HTTPS in production.
Use:
cookie: {
secure: true
}
when your application is running over HTTPS.
3. Use httpOnly
For session cookies:
cookie: {
httpOnly: true
}
This prevents normal client-side JavaScript from reading the cookie.
4. Configure sameSite
For example:
cookie: {
sameSite: "lax"
}
This can provide useful protection against certain cross-site request scenarios.
5. Don't Store Passwords in Sessions
Never do this:
req.session.password = password;
There is no reason to store a user's password in the session.
Instead, store something like:
req.session.userId = user.id;
6. Use a Production Session Store
Don't rely on the default in-memory store for production.
Use a proper shared session store such as Redis or another compatible persistent store.
This becomes especially important when your application runs on multiple servers.
Common Beginner Mistakes
Forgetting to install express-session
npm install express-session
Forgetting to register the middleware
You need:
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false
})
);
before routes that use:
req.session
Using the default memory store in production
The default store is suitable for development and testing, but shouldn't be used as the production session store.
Storing too much data
Don't store an entire user document if you only need the user ID.
Prefer:
req.session.userId = user.id;
Final Thoughts
Sessions provide a convenient way to maintain user state across multiple HTTP requests.
With Express.js, the express-session package makes session management relatively straightforward.
The basic setup is:
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false
})
);
Store data:
req.session.userId = 101;
Read data:
req.session.userId;
Destroy the session:
req.session.destroy();
The most important express-session properties to remember are:
secret
resave
saveUninitialized
cookie
And some important cookie properties are:
maxAge
httpOnly
secure
sameSite
The key idea is simple:
A session allows the server to remember information about a user across multiple HTTP requests, while the browser typically carries a session identifier in a cookie.
Once you understand sessions, the next useful topics are session stores, Redis with express-session, authentication middleware, session-based login systems, and session security.