Skip to main content
← Back to Blog
2026-02-21 · 10 min readWeb DevelopmentUpdated Oct 30, 2026

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.

Avnish Yadav
AI Automation Engineer & Salesforce Developer
16 views
Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies

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 an HttpOnly cookie instead.
  • Cookies bring CSRF risk. SameSite=Strict or Lax helps, 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.

  1. Access token (short-lived): for example 15 minutes. Sent in the Authorization header on API calls.
  2. Refresh token (long-lived): for example 7 days. Used only to get a new access token.
  3. Storage: the refresh token lives in an HttpOnly cookie. 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.

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.

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.

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.

  1. OWASP: HTML5 Security Cheat Sheet (Local Storage)
  2. OWASP: Session Management Cheat Sheet
  3. OWASP: Cross-Site Request Forgery Prevention Cheat Sheet
  4. MDN: Set-Cookie
  5. MDN: Site (glossary)
  6. MDN: Cross-Origin Resource Sharing (CORS)
  7. jwt.io: Introduction to JSON Web Tokens
  8. Express 5: res.cookie()
  9. Axios: Interceptors
  10. Axios: Request config (withCredentials)
  11. Axios: Handling errors
  12. MDN: XMLHttpRequest.withCredentials
  13. react.dev: StrictMode
All 30 parts in this series
  1. Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
  2. Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
  3. Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
  4. Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
  5. Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
  6. Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
  7. Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
  8. Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
  9. Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
  10. Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
  11. Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
  12. Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
  13. Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
  14. Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
  15. Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
  16. Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
  17. Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
  18. Part 18Getting Started with React: Deconstructing JSX and Component Architecture
  19. Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
  20. Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
  21. Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
  22. Part 22React Architecture: Advanced Navigation and Data Flow Patterns
  23. Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
  24. Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
  25. Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
  26. Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
  27. Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
  28. Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
  29. Part 29Introduction to Micro Frontends: Building Scalable Architectures
  30. Part 30The Frontend Architecture: From Junior Developer to Tech Lead
Written by

Avnish Yadav

AI Automation Engineer & Salesforce Developer

Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.

About meLinkedIn

Share
Discussion

Comments

Loading comments...

Add a comment

Comments are reviewed before they appear.