Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
A practical guide to frontend authentication with JWTs. You compare localStorage, in-memory tokens and HttpOnly cookies against XSS and CSRF, set a refresh cookie correctly in Express 5, and build an Axios refresh flow that retries failed requests and shares a refresh call that is already running. The refresh flow was run end to end against a local Express server, with jsdom keeping the cookies.

If you have built a single page app, you have faced this question. The backend hands you a JSON Web Token (JWT). Where do you put it? Many tutorials take the shortest path, localStorage.setItem('token', jwt). It works, it survives reloads, and it is easy. It also hands the token to any script that runs on your page. This guide is for frontend developers who want a safer default. You'll compare the storage options against the two main attacks, then build a refresh flow with an HttpOnly cookie, Express and Axios.
This is part 16 of the Frontend & JavaScript Fundamentals series. It follows REST vs. GraphQL, which covered how the frontend talks to the API. This part covers how it proves who the user is.
Key takeaways
- OWASP says not to keep session identifiers in
localStorage, because any script on the page can read it. Keep the long-lived refresh token in anHttpOnlycookie instead. - Cookies bring CSRF risk.
SameSite=StrictorLaxhelps, but OWASP treats it as defence in depth, not a full CSRF defence. - Keep the short-lived access token in memory and refresh it when the API returns 401, so 401s that arrive during a refresh wait for it.
The threat model: XSS vs. CSRF
A JSON Web Token (JWT) is a compact, signed string that carries claims such as a user id and an expiry time, which the server can check without a session lookup. Where you store it decides which attacks can reach it. Two matter most.
1. Cross-site scripting (XSS)
XSS happens when an attacker gets their JavaScript to run in your page. It can come from a compromised npm package, a third-party script or user input rendered without escaping.
The risk: if the token is in localStorage or sessionStorage, any script on the page can read it with one call and send it to another server. The OWASP HTML5 Security Cheat Sheet says: "Do not store session identifiers in local storage as the data is always accessible by JavaScript." It adds that cookies can reduce this risk with the httpOnly flag.
HttpOnly is not a cure for XSS, though. OWASP's Session Management Cheat Sheet notes that it only protects the cookie's confidentiality. MDN adds that an HttpOnly cookie is still sent with fetch() calls. So injected script can't steal the cookie, but it can still send requests as the user while the page is open.
2. Cross-site request forgery (CSRF)
CSRF happens when another site makes the user's browser send a request to your API. If your API reads a cookie, the browser may attach it, and the API treats the request as genuine.
The trade-off:
| Storage | Readable by XSS? | Sent automatically (CSRF risk)? | Survives reload? | When to use |
|---|---|---|---|---|
localStorage |
Yes | No | Yes | Avoid for tokens (OWASP) |
sessionStorage |
Yes | No | Same tab only | Avoid for tokens |
| Memory (a JS variable) | Only while the page runs | No | No | Short-lived access tokens |
HttpOnly cookie |
No | Yes, limited by SameSite |
Yes | Refresh tokens, sessions |
The verdict: as a rule of thumb, CSRF is easier to contain with SameSite and a CSRF token than every XSS path is to close in a large JavaScript app. So the long-lived secret goes in an HttpOnly cookie, and the short-lived one lives in memory. Keep in mind OWASP's warning that "XSS can defeat all CSRF mitigation techniques." Preventing XSS still comes first.
The architecture: the silent refresh pattern
The goal is a flow that is safe without making users log in all the time. It uses two tokens.
- Access token (short-lived): for example 15 minutes. Sent in the
Authorizationheader on API calls. - Refresh token (long-lived): for example 7 days. Used only to get a new access token.
- Storage: the refresh token lives in an
HttpOnlycookie. The access token lives in a JavaScript variable in memory.
This is often called the "silent refresh" pattern. The lifetimes above are examples; pick yours based on how sensitive the data is.
Step 1: set the cookie on the server (Express 5)
You can't create an HttpOnly cookie from frontend JavaScript. The server must send it in a Set-Cookie header. In the login route, after checking the password, send the refresh token as a cookie and the access token in the body:
// Inside the login route, after the password check
res.cookie('refreshToken', refreshToken, {
httpOnly: true, // client JS can't read it
secure: true, // HTTPS only (see the localhost note below)
sameSite: 'strict', // not sent on cross-site requests
path: '/api/auth', // only sent to /api/auth/refresh and /api/auth/logout
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days, in milliseconds
});
res.json({ accessToken }); // the access token goes in the body
Checked against express@5.3.0, axios@1.21.0 and react@19.3.1 on Node.js 22, 2026-10-30. The run used a local Express server and jsdom as the browser: jsdom kept the cookie, sent it only to /api/auth, and hid it from document.cookie.
Each option maps to a cookie attribute. The Express docs say maxAge is in milliseconds. The browser only sends a cookie to URLs under its Path, so the path must match where the frontend calls the API: here /api/auth, because the Axios setup below uses the base URL /api. OWASP's Session Management Cheat Sheet says to set Path as narrowly as possible and to leave out Domain, so the cookie stays with the host that set it.
SameSite is about sites, not subdomains
An API on api.app.com and a frontend on app.com don't need SameSite=Lax or None. MDN defines a site by its registrable domain, so those two are the same site and Strict works. You need SameSite=None; Secure only when the frontend and API sit on different registrable domains. Cross-origin calls also need CORS with Access-Control-Allow-Credentials: true and an exact origin, never *.
Step 2: the frontend flow with Axios
On the frontend, the hard part is token expiry. When a call fails with 401 Unauthorized, you want to refresh the token and retry the call without the user noticing. Axios interceptors are functions that run before each request and after each response, which makes them the right place for this.
Keep the token in memory
Start with a small module that holds the access token and knows how to refresh it.
// authService.js
import axios from 'axios';
let accessToken = null;
let refreshPromise = null;
export const getAccessToken = () => accessToken;
export const setAccessToken = (token) => {
accessToken = token;
};
// One refresh at a time: 401s that arrive while it runs share it
export function refreshAccessToken() {
refreshPromise ??= axios
.post('/api/auth/refresh', {}, { withCredentials: true })
.then((res) => {
setAccessToken(res.data.accessToken);
return res.data.accessToken;
})
.finally(() => {
refreshPromise = null;
});
return refreshPromise;
}
The refresh call uses the plain axios import, not the instance below. That way, a 401 from the refresh endpoint can't trigger another refresh.
Set up the instance
Create a dedicated Axios instance instead of changing the global one. It keeps the interceptors in one place and makes testing easier.
// api.js
import axios from 'axios';
import { getAccessToken, setAccessToken, refreshAccessToken } from './authService';
const api = axios.create({
baseURL: '/api',
withCredentials: true, // send cookies if the API is on another origin
headers: {
'Content-Type': 'application/json',
},
});
export default api;
The Axios docs say withCredentials controls whether cross-site requests send cookies. MDN's XMLHttpRequest.withCredentials page adds that it has no effect on same-origin requests. So it does nothing while the API shares the page's origin, and it starts to matter if you move the API to another origin.
The request interceptor
This attaches the in-memory access token to every request.
api.interceptors.request.use(
(config) => {
const token = getAccessToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
The response interceptor
This is the core of the flow. It catches a 401, refreshes the token once, and retries the original request.
api.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config;
// No response means a network error, so there is nothing to refresh
if (error.response?.status === 401 && originalRequest && !originalRequest._retry) {
originalRequest._retry = true; // retry each request only once
try {
const token = await refreshAccessToken();
originalRequest.headers.Authorization = `Bearer ${token}`;
return api(originalRequest);
} catch (refreshError) {
// The refresh token is invalid or expired: send the user to log in
setAccessToken(null);
window.location.assign('/login');
return Promise.reject(refreshError);
}
}
return Promise.reject(error);
}
);
Fixed in this version
The earlier code read error.response.status directly. The Axios error guide shows that error.response is missing when no response arrives, so a network error crashed the interceptor. It also called an undefined setAccessToken, and when several requests failed together, each started its own refresh. Now any 401 that arrives while a refresh is running waits for that same call. A 401 that arrives after it finishes starts a new, still valid refresh.
Step 3: stay logged in after a reload
The access token lives in memory, so a page reload wipes it. The refresh cookie survives, though. When the app starts, ask for a new access token before rendering anything that needs one.
// AuthProvider.jsx
import { createContext, useEffect, useState } from 'react';
import { refreshAccessToken } from './authService';
export const AuthContext = createContext({ isAuthenticated: false });
export function AuthProvider({ children }) {
const [status, setStatus] = useState('loading');
useEffect(() => {
// The HttpOnly cookie survived the reload, so try to refresh
refreshAccessToken()
.then(() => setStatus('authenticated'))
.catch(() => setStatus('anonymous'));
}, []);
if (status === 'loading') return <p>Loading…</p>;
return (
<AuthContext.Provider value={{ isAuthenticated: status === 'authenticated' }}>
{children}
</AuthContext.Provider>
);
}
With this flow, the user stays signed in across reloads. The app starts, calls /api/auth/refresh, gets a new access token and carries on. In development, the react.dev Strict Mode page says React runs an extra setup and cleanup cycle for every Effect. The shared refresh promise means both runs reuse the same request.
Common pitfalls
1. Putting sensitive data in the JWT
A signed JWT is not encrypted. jwt.io explains that the header and payload are only Base64Url encoded, and that the content is "readable by anyone." Don't put passwords, personal data or API keys in the payload. Stick to an id, a role and the expiry (exp).
2. Skipping CSRF defences because "it's a React app"
If the API trusts a cookie, CSRF applies, whatever the frontend framework. OWASP's CSRF cheat sheet says SameSite "does not replace a proper CSRF defense in most deployments." Its main defences are the synchronizer token pattern for stateful apps and the signed double-submit cookie for stateless ones. For JSON APIs, requiring a custom request header is another option it lists.
3. Turning off Secure for local development
Older guides check NODE_ENV and drop Secure on localhost. MDN's Set-Cookie page says the HTTPS requirement is ignored when localhost sets a Secure cookie, so in Chrome and Firefox you can keep secure: true on http://localhost. MDN's compatibility table notes one exception: Safari doesn't send Secure cookies to http://localhost. If you test in Safari, serve your dev site over HTTPS rather than turning Secure off, so a misconfigured environment can't ship cookies over plain HTTP.
Build for resilience
Storing a token correctly takes more work than dropping it into localStorage. The result is worth it. The long-lived refresh token is out of reach of injected scripts. The short-lived access token disappears when the tab closes. And the refresh flow keeps users signed in without them noticing.
Next in the series, why TypeScript matters adds types to code like the auth service above, so a missing token is caught before it ships.
Frequently asked questions
Is it safe to store a JWT in localStorage?
Not for session tokens. OWASP's HTML5 Security Cheat Sheet says not to store session identifiers in local storage, because any JavaScript on the page can read it. A single XSS bug would expose every token stored there.
Does an HttpOnly cookie stop XSS?
No. It stops scripts from reading the cookie, so the attacker can't take it away and reuse it later. While the attack runs in the user's tab, though, the browser still attaches the cookie to requests. Preventing XSS is still the main defence.
Do I still need CSRF protection with SameSite=Strict?
Usually yes, as a second layer. OWASP calls SameSite defence in depth and recommends a CSRF token or a custom request header as the main control. Strict also blocks the cookie on links from other sites, which suits a refresh endpoint.
Why keep the access token in memory instead of a cookie?
A short-lived token in memory is gone when the tab closes and isn't sent automatically, so CSRF can't use it. If XSS reads it, it expires within minutes. The refresh cookie restores it after a reload.
What should logout do?
Call a logout endpoint that revokes the refresh token on the server and clears the cookie with the same options it was set with, including path. Then clear the in-memory access token. Clearing only the frontend state leaves a valid refresh token behind.
app.post('/api/auth/logout', (req, res) => {
// Revoke the refresh token in your database here, then clear the cookie
res.clearCookie('refreshToken', { httpOnly: true, secure: true, sameSite: 'strict', path: '/api/auth' });
res.sendStatus(204);
});
Sources
Verified against the sources below on October 30, 2026. Products and docs change often: check the linked sources if something looks different.
- OWASP: HTML5 Security Cheat Sheet (Local Storage)
- OWASP: Session Management Cheat Sheet
- OWASP: Cross-Site Request Forgery Prevention Cheat Sheet
- MDN: Set-Cookie
- MDN: Site (glossary)
- MDN: Cross-Origin Resource Sharing (CORS)
- jwt.io: Introduction to JSON Web Tokens
- Express 5: res.cookie()
- Axios: Interceptors
- Axios: Request config (withCredentials)
- Axios: Handling errors
- MDN: XMLHttpRequest.withCredentials
- react.dev: StrictMode
All 30 parts in this series
- Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
- Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
- Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
- Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
- Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
- Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
- Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
- Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
- Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
- Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
- Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
- Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
- Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
- Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
- Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
- Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
- Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
- Part 18Getting Started with React: Deconstructing JSX and Component Architecture
- Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
- Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
- Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
- Part 22React Architecture: Advanced Navigation and Data Flow Patterns
- Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
- Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
- Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
- Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
- Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
- Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
- Part 29Introduction to Micro Frontends: Building Scalable Architectures
- Part 30The Frontend Architecture: From Junior Developer to Tech Lead



Comments
Loading comments...