JWT Authentication in a MERN App: Access Tokens, Refresh Tokens and httpOnly Cookies
By Muhammad Osama Khan, Software Engineer. Auth, Oct 6, 2026, 4 min read.
Keep the access token in memory, the refresh token in an httpOnly cookie, and retry once on a 401. A complete flow with Express and React code.
Most MERN tutorials store the JWT in localStorage and call it done. It works, but any script that runs on your page (an XSS bug, a compromised dependency) can read it and keep using it. A safer setup is small: a short-lived access token that lives only in memory, and a longer-lived refresh token that the browser keeps in an httpOnly cookie that JavaScript cannot read.
The flow in five steps
- The user logs in. The API checks the password and returns an access token in the JSON body (valid for about 15 minutes) and sets a refresh token cookie (valid for days).
- React keeps the access token in a module variable, not in storage, and sends it as a
Bearerheader. - When the API answers
401, React calls/api/auth/refresh. The browser attaches the cookie automatically. - The API verifies the refresh token and returns a new access token.
- React retries the original request once. If the refresh also fails, the user is sent to the login page.
Login and token creation in Express
Hash passwords with bcrypt, never compare them in plain text, and use two different secrets so a leaked access secret cannot forge refresh tokens.
server/routes/auth.js
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
import User from '../models/User.js';
const ACCESS_TTL = '15m';
const REFRESH_TTL_MS = 7 * 24 * 60 * 60 * 1000;
const signAccess = (user) =>
jwt.sign({ sub: user._id, role: user.role }, process.env.JWT_ACCESS_SECRET, { expiresIn: ACCESS_TTL });
const signRefresh = (user) =>
jwt.sign({ sub: user._id }, process.env.JWT_REFRESH_SECRET, { expiresIn: '7d' });
export const login = async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
// same message for "no such user" and "wrong password"
if (!user || !(await bcrypt.compare(password, user.passwordHash))) {
return res.status(401).json({ message: 'Invalid email or password' });
}
res.cookie('refreshToken', signRefresh(user), {
httpOnly: true, // JavaScript cannot read it
secure: process.env.NODE_ENV === 'production', // HTTPS only in production
sameSite: 'strict',
path: '/api/auth', // only sent to the auth routes
maxAge: REFRESH_TTL_MS
});
res.json({ accessToken: signAccess(user), user: { id: user._id, name: user.name } });
};Protecting routes and refreshing
server/middleware/requireAuth.js
import jwt from 'jsonwebtoken';
export const requireAuth = (req, res, next) => {
const header = req.headers.authorization || '';
const token = header.startsWith('Bearer ') ? header.slice(7) : null;
if (!token) return res.status(401).json({ message: 'Missing token' });
try {
req.user = jwt.verify(token, process.env.JWT_ACCESS_SECRET);
next();
} catch {
res.status(401).json({ message: 'Invalid or expired token' });
}
};server/routes/auth.js
export const refresh = async (req, res) => {
const token = req.cookies.refreshToken; // needs the cookie-parser middleware
if (!token) return res.status(401).json({ message: 'No refresh token' });
try {
const payload = jwt.verify(token, process.env.JWT_REFRESH_SECRET);
const user = await User.findById(payload.sub);
if (!user) return res.status(401).json({ message: 'User not found' });
res.json({ accessToken: signAccess(user) });
} catch {
res.status(401).json({ message: 'Refresh token expired' });
}
};
export const logout = (req, res) => {
res.clearCookie('refreshToken', { path: '/api/auth' });
res.status(204).end();
};CORS must allow credentials
If React and the API live on different origins, cookies are only sent when both sides opt in. The API needs an explicit origin (a wildcard is rejected when credentials are on), and every fetch needs credentials: 'include'.
server/app.js
import cors from 'cors';
import cookieParser from 'cookie-parser';
app.use(cors({ origin: process.env.CLIENT_URL, credentials: true }));
app.use(cookieParser());A fetch wrapper in React that retries once
client/src/lib/api.js
let accessToken = null; // in memory only: gone on refresh, restored by /refresh
export const setAccessToken = (token) => { accessToken = token; };
const request = (path, options = {}) =>
fetch('/api' + path, {
...options,
credentials: 'include',
headers: {
'Content-Type': 'application/json',
...(accessToken ? { Authorization: 'Bearer ' + accessToken } : {}),
...options.headers
}
});
export const api = async (path, options) => {
let res = await request(path, options);
if (res.status === 401) {
const refreshed = await fetch('/api/auth/refresh', { method: 'POST', credentials: 'include' });
if (!refreshed.ok) {
setAccessToken(null);
throw new Error('Session expired');
}
setAccessToken((await refreshed.json()).accessToken);
res = await request(path, options); // retry once
}
return res;
};Hardening it further
- Store a hash of each refresh token in the database and rotate it on every refresh, so a stolen token stops working after one use and you can revoke sessions.
- If the front end and API are on different sites (not just different subdomains),
sameSite: 'strict'blocks the cookie; you then needsameSite: 'none'withsecure: true, and CSRF protection becomes more important. - Rate-limit the login route and keep access tokens short. Do not put anything secret in the payload: it is only signed, not encrypted.
Frequently asked questions
Where should I store a JWT in a React app?
Keep the short-lived access token in memory (a variable in a module) and the refresh token in an httpOnly cookie. Anything in localStorage can be read by any script that runs on your page, so a single XSS bug exposes it.
How long should a JWT access token last?
Short: commonly 5 to 15 minutes. A short life limits the damage if a token leaks, and the refresh token gets a new one without asking the user to sign in again. Refresh tokens usually last days.
Why does my refresh token cookie not reach the API?
When React and the API are on different origins, the cookie is only sent if every fetch uses credentials: 'include', the API enables CORS with credentials: true and an explicit origin (not *), and the cookie's SameSite and Secure settings match your setup. Cross-site cookies need SameSite=None with Secure.
Do I need a refresh token at all?
Not always. For a small app, a single session cookie with a sensible lifetime is simpler. Refresh tokens are worth it when you want very short-lived access tokens without making people log in again.