DEV Community

M.Nadeem Shakoor
M.Nadeem Shakoor

Posted on

Cookie Auth vs Bearer Token in Express – What's the Difference and When to Use Each?

When building secure Express.js applications, you’ll likely face a key architectural choice:
Should you use cookie-based authentication or bearer tokens like JWTs?

Each method has unique advantages depending on your frontend, deployment, and security requirements. In this post, we’ll break it down clearly and practically.

Why It Matters
Defines how your app handles sessions and security
Impacts frontend integration, especially for SPAs
Affects protection against attacks like CSRF and XSS
Determines whether tokens are sent automatically or manually
Option 1: Cookie-Based Authentication
How It Works
Server sets a cookie containing a session ID or JWT
Browser stores it and automatically sends it with every request — if configured correctly
res.cookie('token', jwtToken, {
httpOnly: true,
secure: true,
sameSite: 'Strict'
});
To access it:

import cookieParser from 'cookie-parser';
app.use(cookieParser());

app.get('/dashboard', (req, res) => {
const token = req.cookies.token;
});
When Are Cookies Sent Automatically?
Cookies are included in requests when:

The origin matches the cookie's domain
sameSite allows the request (Lax, Strict, or None)
credentials: 'include' is used in fetch/axios for cross-origin requests
Connection is over HTTPS if secure: true
fetch('https://api.example.com/user', {
credentials: 'include'
});
Option 2: Bearer Token Authentication (JWT)
How It Works
Client stores token manually (e.g., in localStorage)
Token is explicitly added to the Authorization header
fetch('/api/protected', {
headers: {
Authorization: Bearer ${token}
}
});
On the backend:

const authHeader = req.headers.authorization;
const token = authHeader?.split(' ')[1];

Top comments (0)