Cookies are a common part of web applications.
You may have seen websites remember things like:
- Login sessions
- User preferences
- Language selection
- Theme selection
- Shopping cart information
- Authentication-related session identifiers
In Express.js, working with cookies is straightforward, but there are a few important concepts to understand.
In this article, we'll learn:
- What cookies are
- How cookies work
- How to create cookies in Express.js
- How to read cookies
- How to delete cookies
- What
cookie-parserdoes - What signed cookies are
- The difference between normal and signed cookies
- Important cookie security options
What Is a Cookie?
A cookie is a small piece of data that a server asks the browser to store.
For example, a server might send:
userTheme=dark
The browser stores this information and can send it back to the server with later requests.
A simplified flow looks like this:
Browser
↓
Request
↓
Express Server
↓
Set-Cookie
↓
Browser stores cookie
↓
Future Request
↓
Cookie sent back to server
Cookies are stored by the browser and are associated with a particular domain and other cookie attributes.
Creating a Basic Express.js Application
Let's start with a simple Express application.
const express = require("express");
const app = express();
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Now let's see how to create a cookie.
Creating a Cookie With res.cookie()
Express provides res.cookie() for setting cookies.
app.get("/set-cookie", (req, res) => {
res.cookie("username", "John");
res.send("Cookie created");
});
When the browser requests:
GET /set-cookie
Express sends a response containing a Set-Cookie header.
Conceptually:
Set-Cookie: username=John
The browser then stores the cookie.
Reading Cookies
To read cookies easily, we commonly use the cookie-parser middleware.
First, install it:
npm install cookie-parser
Then import it:
const cookieParser = require("cookie-parser");
Register the middleware:
app.use(cookieParser());
Now you can access cookies through:
req.cookies
For example:
app.get("/profile", (req, res) => {
console.log(req.cookies);
res.json(req.cookies);
});
If the browser sends:
Cookie: username=John
you can access:
req.cookies.username
which gives:
John
Complete Cookie Example
const express = require("express");
const cookieParser = require("cookie-parser");
const app = express();
app.use(cookieParser());
app.get("/set-cookie", (req, res) => {
res.cookie("username", "John");
res.send("Cookie created");
});
app.get("/get-cookie", (req, res) => {
const username = req.cookies.username;
res.json({
username
});
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Now:
GET /set-cookie
creates the cookie.
And:
GET /get-cookie
reads it.
What Is cookie-parser?
cookie-parser is Express middleware that parses the Cookie request header and makes cookies available through:
req.cookies
Without it, you would need to manually parse the cookie header.
For example:
app.get("/", (req, res) => {
console.log(req.cookies);
});
With:
app.use(cookieParser());
you can easily access:
req.cookies.username
cookie-parser Is Middleware
It is important to understand that cookie-parser isn't part of Express's core middleware.
You install it separately:
npm install cookie-parser
Then:
const cookieParser = require("cookie-parser");
app.use(cookieParser());
After this middleware runs, Express can access parsed cookies through:
req.cookies
Cookie Options
Cookies can have different options.
For example:
res.cookie("username", "John", {
maxAge: 60 * 60 * 1000
});
Here:
maxAge = 1 hour
because:
60 * 60 * 1000
equals one hour in milliseconds.
Common Cookie Options
Some commonly used options are:
maxAge
Defines how long the cookie should remain valid.
res.cookie("username", "John", {
maxAge: 60 * 60 * 1000
});
expires
Specifies an exact expiration date.
res.cookie("username", "John", {
expires: new Date(Date.now() + 60 * 60 * 1000)
});
httpOnly
Prevents client-side JavaScript from accessing the cookie through document.cookie.
res.cookie("sessionId", "abc123", {
httpOnly: true
});
This is particularly important for cookies containing sensitive session information.
secure
When set to true, the browser only sends the cookie over HTTPS.
res.cookie("sessionId", "abc123", {
secure: true
});
During local HTTP development, you may need different configuration.
sameSite
Controls when cookies are sent in cross-site requests.
For example:
res.cookie("sessionId", "abc123", {
httpOnly: true,
secure: true,
sameSite: "strict"
});
Common values include:
strict
lax
none
The correct choice depends on your application's architecture.
Example of a More Secure Cookie
For a session identifier, you might use:
res.cookie("sessionId", "abc123", {
httpOnly: true,
secure: true,
sameSite: "lax",
maxAge: 60 * 60 * 1000
});
The important thing to remember is that cookie security depends on the application's requirements.
Deleting a Cookie
Express provides res.clearCookie().
app.get("/logout", (req, res) => {
res.clearCookie("sessionId");
res.send("Logged out");
});
The browser will remove the cookie.
When clearing cookies, make sure the relevant cookie attributes are consistent with how the cookie was originally set.
What Are Signed Cookies?
A normal cookie can be modified by the client.
For example:
role=user
A user can potentially modify the value stored in their browser to:
role=admin
A signed cookie helps the server detect whether the cookie value has been modified after it was created.
The important point is:
A signed cookie provides integrity checking, not encryption.
The cookie value is not hidden from the client just because it is signed.
Creating Signed Cookies
To use signed cookies with cookie-parser, provide a secret:
app.use(cookieParser("my-secret-key"));
Now create a signed cookie:
app.get("/set-cookie", (req, res) => {
res.cookie("userId", "101", {
signed: true
});
res.send("Signed cookie created");
});
Reading Signed Cookies
Normal cookies are available through:
req.cookies
Signed cookies are available through:
req.signedCookies
For example:
app.get("/get-cookie", (req, res) => {
const userId = req.signedCookies.userId;
res.json({
userId
});
});
So remember:
Normal cookie
→ req.cookies
Signed cookie
→ req.signedCookies
Complete Signed Cookie Example
const express = require("express");
const cookieParser = require("cookie-parser");
const app = express();
app.use(cookieParser("my-secret-key"));
app.get("/set-cookie", (req, res) => {
res.cookie("userId", "101", {
signed: true,
httpOnly: true
});
res.send("Signed cookie created");
});
app.get("/get-cookie", (req, res) => {
const userId = req.signedCookies.userId;
res.json({
userId
});
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
How Signed Cookies Work
The basic idea is:
Cookie value
+
Secret key
↓
Signature
The server sends the cookie along with a signature.
Later, when the browser sends the cookie back, cookie-parser can verify the signature using the secret.
If the value has been modified, the signature won't match.
Conceptually:
Original:
userId=101
signature=ABC
Attacker changes:
userId=999
signature=ABC
↓
Signature verification fails
The server can therefore detect that the cookie was tampered with.
Signed Cookies Are Not Encrypted
This is one of the most important points.
Suppose you have:
res.cookie("userId", "101", {
signed: true
});
Signing does not mean that "101" becomes secret.
The user can still potentially see the cookie.
Signing provides:
Integrity
It does not provide:
Confidentiality
If sensitive information needs to be kept secret, don't put the sensitive information directly into a cookie just because it is signed.
A common pattern is to store a random session identifier in the cookie and keep sensitive session data on the server.
Normal Cookies vs Signed Cookies
Normal cookie
res.cookie("userId", "101");
Read using:
req.cookies.userId;
Signed cookie
res.cookie("userId", "101", {
signed: true
});
Read using:
req.signedCookies.userId;
The key difference is that signed cookies allow the server to detect tampering.
A Practical Authentication Example
Cookies are often used with session-based authentication.
A simplified flow might look like this:
User logs in
↓
Server validates credentials
↓
Server creates session
↓
Server sends session ID in cookie
↓
Browser stores cookie
↓
Browser sends cookie with future requests
↓
Server identifies the session
For example:
res.cookie("sessionId", sessionId, {
httpOnly: true,
secure: true,
sameSite: "lax"
});
The browser then automatically sends the cookie with appropriate requests.
The server can use the session ID to identify the authenticated user.
Important Security Considerations
When cookies are used for authentication, don't treat them as ordinary data.
Use httpOnly
httpOnly: true
This helps prevent JavaScript from reading the cookie.
Use secure in HTTPS environments
secure: true
This ensures the browser sends the cookie only over HTTPS.
Configure sameSite appropriately
sameSite: "lax"
or another appropriate value depending on your application's requirements.
Don't store sensitive data directly in cookies
Avoid putting things like:
passwords
private information
database credentials
API secrets
inside cookies.
Cookies are controlled by the client, so they should never be treated as a secure database.
Common Mistakes
1. Forgetting cookie-parser
If you're using req.cookies and haven't registered the middleware:
app.use(cookieParser());
you won't get the expected parsed cookie object.
2. Reading a signed cookie from req.cookies
If you create:
res.cookie("userId", "101", {
signed: true
});
read it using:
req.signedCookies.userId;
not:
req.cookies.userId;
3. Thinking signed means encrypted
A signed cookie isn't encrypted.
Its purpose is to help detect modification.
4. Using a weak secret
If you're using signed cookies:
app.use(cookieParser("my-secret-key"));
don't use a predictable secret in a real application.
Use a strong secret and keep it outside your source code, commonly through environment variables:
COOKIE_SECRET=your-strong-secret
Then:
app.use(cookieParser(process.env.COOKIE_SECRET));
Complete Example
Here's a small example combining normal cookies, signed cookies, reading cookies, and deleting cookies:
const express = require("express");
const cookieParser = require("cookie-parser");
const app = express();
app.use(cookieParser(process.env.COOKIE_SECRET));
app.get("/set", (req, res) => {
// Normal cookie
res.cookie("theme", "dark");
// Signed cookie
res.cookie("userId", "101", {
signed: true,
httpOnly: true
});
res.json({
message: "Cookies created"
});
});
app.get("/get", (req, res) => {
const theme = req.cookies.theme;
const userId = req.signedCookies.userId;
res.json({
theme,
userId
});
});
app.get("/logout", (req, res) => {
res.clearCookie("theme");
res.clearCookie("userId");
res.json({
message: "Cookies cleared"
});
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Final Thoughts
Cookies are an important part of modern web applications, especially when implementing sessions and authentication.
In Express.js, you can create cookies using:
res.cookie()
Read normal cookies using:
req.cookies
And read signed cookies using:
req.signedCookies
cookie-parser makes cookie handling much easier:
app.use(cookieParser());
For signed cookies:
app.use(cookieParser(process.env.COOKIE_SECRET));
and:
res.cookie("userId", "101", {
signed: true
});
The most important concept to remember is:
A normal cookie stores data, while a signed cookie adds integrity checking so the server can detect whether the cookie has been tampered with.
Also remember that signed cookies are not encrypted cookies. For authentication, use appropriate cookie attributes such as httpOnly, secure, and sameSite, and avoid storing sensitive information directly in the cookie.