Originally published on PEAKIQ

Source: https://www.peakiq.in/blog/stop-treating-jwt-authentication-as-just-a-login-secure-mern-auth

Stop Treating JWT Authentication as Just a Login — Secure MERN Auth in 2026

Most tutorials teach authentication as a simple three-step process:

  1. User submits email and password.
  2. Server validates credentials.
  3. Server generates a JWT and returns it.

That works for a demo.

But production authentication is not just about verifying credentials and generating a token. It is about protecting sessions, handling expired credentials, managing concurrent requests, preventing token theft, revoking access, and keeping the application secure without breaking the user experience.

In 2026, building authentication for a MERN application means thinking beyond the login endpoint.

You need an authentication architecture that can handle:

  • Access token expiration
  • Refresh token rotation
  • Secure token storage
  • Session revocation
  • Multiple devices
  • Concurrent API requests
  • XSS and CSRF risks
  • Logout and account security
  • API scaling

This is the architecture I would use for a production MERN application.

1. The Authentication Stack

For this architecture, we are using a modern MERN stack with a clear separation between authentication, session management, and application APIs.

Frontend

  • React
  • TypeScript
  • Axios
  • Zustand or Redux Toolkit
  • React Router
  • TanStack Query

Backend

  • Node.js
  • Express
  • TypeScript
  • MongoDB
  • JWT access tokens
  • Refresh token sessions
  • HttpOnly cookies
  • Zod validation
  • Rate limiting

The goal is not to add more dependencies.

The goal is to make authentication predictable, secure, and easy to maintain.

2. The Three Problems Most JWT Tutorials Ignore

Before writing code, we need to understand the real problems.

Problem 1: Token Exposure

If you store long-lived authentication tokens in localStorage, any JavaScript running within your origin that is compromised through XSS may be able to read those tokens.

A stolen token can become a stolen session.

Problem 2: Session Lifecycle

JWTs are stateless, but production applications still need state.

You need to know:

  • Is the user logged out?
  • Is this device still authorized?
  • Has the refresh token been rotated?
  • Has the session been revoked?
  • Has the account been disabled?

Problem 3: Concurrent Requests

Imagine a user opens the dashboard and 10 API requests start simultaneously.

The access token expires.

All 10 requests receive a 401 Unauthorized.

If every request independently calls the refresh endpoint, you can end up with:

  • 10 refresh requests
  • Refresh token rotation conflicts
  • Some requests succeeding while others fail
  • Unexpected logout
  • Duplicate retries

This is why authentication needs to be designed as a system rather than a single endpoint.

3. Stop Storing Long-Lived JWTs in localStorage

The most common implementation looks like this:

localStorage.setItem("token", accessToken); 

And then:

const token = localStorage.getItem("token"); 

This is convenient, but it creates a major security trade-off.

JavaScript can access localStorage. If an attacker executes JavaScript through an XSS vulnerability, they may extract the stored token.

Instead, separate the responsibilities.

Token Storage Purpose
Access token In-memory state Authenticate API requests
Refresh token HttpOnly cookie Renew authentication
Refresh token hash MongoDB Validate and revoke sessions

The access token should be short-lived.

The refresh token should be protected by the browser and managed by the server.

The server should store a hash of the refresh token rather than the raw token.

This reduces the impact of a database leak.

4. Authentication Architecture

The authentication lifecycle looks like this:

flowchart TD A[User Login] --> B[Validate Credentials] B --> C[Create Session] C --> D[Generate Access Token] C --> E[Generate Refresh Token] D --> F[Return Access Token] E --> G[Set HttpOnly Cookie] F --> H[React Stores Token in Memory] H --> I[API Request] I --> J{Access Token Valid?} J -->|Yes| K[Return API Response] J -->|No| L[Refresh Endpoint] L --> M[Validate Refresh Session] M --> N[Rotate Refresh Token] N --> O[Issue New Access Token] O --> P[Retry Original Request] 

The important difference is that the refresh token is never returned inside the JSON response.

The browser stores it in a protected cookie.

5. Short-Lived Access Tokens

Access tokens should not remain valid for days.

For most applications, a short lifetime such as 10–15 minutes is a reasonable starting point. The exact duration depends on the application's threat model and usability requirements.

Example JWT payload:

{ "sub": "user_123", "sid": "session_456", "iss": "api.peakiq.in", "aud": "peakiq-client", "iat": 1764200000, "exp": 1764200900 } 

The token contains:

  • sub — user ID
  • sid — session ID
  • iss — issuer
  • aud — intended audience
  • iat — issued at
  • exp — expiration

Do not put sensitive user data into JWT payloads.

JWT payloads are encoded, not encrypted.

Access token generation

import jwt from "jsonwebtoken"; export function createAccessToken( userId: string, sessionId: string ) { return jwt.sign( { sid: sessionId, }, process.env.ACCESS_TOKEN_SECRET!, { subject: userId, issuer: "api.peakiq.in", audience: "peakiq-client", expiresIn: "15m", algorithm: "HS256", } ); } 

In production, keep signing secrets outside your source code and use strong, separate secrets for access and refresh token mechanisms.

6. Refresh Tokens Are Sessions

The refresh token is what keeps the user logged in after the access token expires.

Instead of treating refresh tokens as permanent credentials, treat them as sessions that can be:

  • Rotated
  • Revoked
  • Expired
  • Audited
  • Associated with a device

I prefer using a cryptographically random opaque refresh token instead of a long-lived JWT refresh token.

import crypto from "node:crypto"; export function createRefreshToken() { return crypto.randomBytes(64).toString("hex"); } export function hashRefreshToken(token: string) { return crypto .createHash("sha256") .update(token) .digest("hex"); } 

The refresh token itself is sent to the browser.

The hash is stored in MongoDB.

7. MongoDB Session Model

A session collection gives us control over authentication beyond JWT expiration.

import { Schema, model } from "mongoose"; const authSessionSchema = new Schema( { userId: { type: Schema.Types.ObjectId, ref: "User", required: true, index: true, }, refreshTokenHash: { type: String, required: true, unique: true, }, deviceName: String, ipAddress: String, userAgent: String, expiresAt: { type: Date, required: true, }, revokedAt: { type: Date, default: null, }, }, { timestamps: true, } ); authSessionSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 }); authSessionSchema.index({ userId: 1, revokedAt: 1 }); export const AuthSession = model( "AuthSession", authSessionSchema ); 

This gives us a foundation for:

  • Logout
  • Device management
  • Session expiration
  • Revoking individual devices
  • Revoking all sessions
  • Security audit trails

The TTL index is cleanup automation. It is not a substitute for checking session expiration in the authentication logic.

8. Login: Create the Session

When the user successfully authenticates, create:

  1. A session ID
  2. An access token
  3. A refresh token
  4. A hashed refresh token stored in MongoDB
  5. An HttpOnly cookie containing the refresh token
import crypto from "node:crypto"; import { AuthSession } from "../models/auth-session"; import { createAccessToken } from "../utils/access-token"; import { createRefreshToken, hashRefreshToken } from "../utils/refresh-token"; export async function createAuthSession( userId: string, res: any ) { const sessionId = crypto.randomUUID(); const refreshToken = createRefreshToken(); const refreshTokenHash = hashRefreshToken(refreshToken); await AuthSession.create({ userId, refreshTokenHash, expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), }); const accessToken = createAccessToken(userId, sessionId); res.cookie("refreshToken", refreshToken, { httpOnly: true, secure: process.env.NODE_ENV === "production", sameSite: "strict", path: "/api/auth", maxAge: 7 * 24 * 60 * 60 * 1000, }); return { accessToken, }; } 

Notice what we return.

{ "accessToken": "..." } 

We do not return the refresh token.

The refresh token is delivered through the cookie.

The cookie configuration must match your deployment topology. If your frontend and backend are cross-site, you may need SameSite=None with Secure, plus appropriate CSRF protections.

9. Refresh Token Rotation

A refresh endpoint is one of the most important parts of authentication.

When a refresh token is used:

  1. Validate the existing token.
  2. Hash it.
  3. Find the matching session.
  4. Reject expired or revoked sessions.
  5. Generate a new refresh token.
  6. Replace the stored hash.
  7. Issue a new access token.
  8. Update the browser cookie.
import { Request, Response } from "express"; import { AuthSession } from "../models/auth-session"; import { hashRefreshToken, createRefreshToken } from "../utils/refresh-token"; import { createAccessToken } from "../utils/access-token"; export async function refreshSession( req: Request, res: Response ) { const currentToken = req.cookies.refreshToken; if (!currentToken) { return res.status(401).json({ message: "Authentication required", }); } const currentHash = hashRefreshToken(currentToken); const session = await AuthSession.findOne({ refreshTokenHash: currentHash, revokedAt: null, expiresAt: { $gt: new Date() }, }); if (!session) { return res.status(401).json({ message: "Session expired or invalid", }); } const nextRefreshToken = createRefreshToken(); const nextHash = hashRefreshToken(nextRefreshToken); const updated = await AuthSession.findOneAndUpdate( { _id: session._id, refreshTokenHash: currentHash, revokedAt: null, }, { $set: { refreshTokenHash: nextHash, }, }, { new: true, } ); if (!updated) { return res.status(401).json({ message: "Session no longer valid", }); } const accessToken = createAccessToken( session.userId.toString(), session._id.toString() ); res.cookie("refreshToken", nextRefreshToken, { httpOnly: true, secure: process.env.NODE_ENV === "production", sameSite: "strict", path: "/api/auth", maxAge: 7 * 24 * 60 * 60 * 1000, }); return res.json({ accessToken, }); } 

Why rotation matters

If a refresh token is stolen and then reused after the legitimate user has rotated it, that reuse can be a signal of token theft.

A production implementation should consider refresh token reuse detection and session-family revocation. It should also handle refresh requests that race with one another, because strict rotation can cause legitimate concurrent requests to fail if coordination is missing.

10. React: Keep the Access Token in Memory

The frontend only needs the access token to make API requests.

You can store it in Zustand:

import { create } from "zustand"; type AuthState = { accessToken: string | null; setAccessToken: (token: string | null) => void; }; export const useAuthStore = create<AuthState>((set) => ({ accessToken: null, setAccessToken: (accessToken) => { set({ accessToken }); }, })); 

This token disappears when the application reloads.

That is intentional.

On application startup, the frontend calls the refresh endpoint. The browser sends the HttpOnly cookie automatically, and the backend issues a new access token if the session is still valid.

11. Axios: Handle Expired Tokens Automatically

A production application cannot ask users to log in again every 15 minutes.

Axios interceptors can handle token expiration automatically.

The architecture needs to:

  • Add the access token to outgoing requests.
  • Detect authentication failures.
  • Refresh the session.
  • Retry the original request.
  • Prevent multiple simultaneous refresh calls.

Axios client

import axios from "axios"; export const api = axios.create({ baseURL: import.meta.env.VITE_API_URL, withCredentials: true, }); 

Request interceptor

import { useAuthStore } from "../store/auth-store"; api.interceptors.request.use((config) => { const token = useAuthStore.getState().accessToken; if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }); 

The access token remains in memory and is attached to requests only when needed.

12. Prevent Multiple Refresh Requests

This is where many applications become unreliable.

If 10 requests fail simultaneously, they should not trigger 10 refresh requests.

Instead, use a single shared refresh operation within the current JavaScript runtime.

let refreshPromise: Promise<string> | null = null; async function refreshAccessToken() { if (!refreshPromise) { refreshPromise = api .post("/api/auth/refresh") .then((response) => { const accessToken = response.data.accessToken; useAuthStore.getState().setAccessToken(accessToken); return accessToken; }) .finally(() => { refreshPromise = null; }); } return refreshPromise; } 

This ensures requests in the same tab share one refresh operation.

It does not coordinate refresh requests across multiple browser tabs. Multi-tab coordination may require an additional mechanism such as BroadcastChannel, shared state, or server-side handling of rotation races.

13. Retry the Original Request

Once the refresh completes, retry the original API request with the new access token.

api.interceptors.response.use( (response) => response, async (error) => { const originalRequest = error.config; if ( error.response?.status === 401 && originalRequest && !originalRequest._retry && !originalRequest.url?.includes("/auth/refresh") ) { originalRequest._retry = true; try { const accessToken = await refreshAccessToken(); originalRequest.headers.Authorization = \`Bearer \${accessToken}\`; return api(originalRequest); } catch (refreshError) { useAuthStore.getState().setAccessToken(null); return Promise.reject(refreshError); } } return Promise.reject(error); } ); 

The _retry flag prevents infinite retry loops.

Without it, a failed retry could trigger another refresh indefinitely.

14. Application Startup Authentication

When React starts, it does not know whether the user has an active session.

The access token is stored only in memory, so the application needs to restore authentication.

export async function restoreSession() { try { const response = await api.post("/api/auth/refresh"); useAuthStore.getState().setAccessToken( response.data.accessToken ); return true; } catch { useAuthStore.getState().setAccessToken(null); return false; } } 

Use this during application bootstrap.

While session restoration is in progress, show a loading state instead of briefly rendering the login screen.

This prevents unnecessary redirects and improves the user experience.

15. HttpOnly Cookies, CORS, and CSRF

Using HttpOnly cookies solves one problem.

It does not solve every authentication security problem.

Cookie configuration

res.cookie("refreshToken", refreshToken, { httpOnly: true, secure: true, sameSite: "strict", path: "/api/auth", }); 

What these options do

Option Purpose
HttpOnly Prevent JavaScript from reading the cookie
Secure Send the cookie only over HTTPS
SameSite Restrict cross-site cookie behavior
Source:https://dev.to/peakiqofficial/secure-mern-jwt-authentication-beyond-simple-login-36oh

Related posts