DEV Community

Cover image for Secure MERN JWT Authentication: Beyond Simple Login
PEAKIQ
PEAKIQ

Posted on Originally published at peakiq.in

Secure MERN JWT Authentication: Beyond Simple Login

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);
Enter fullscreen mode Exit fullscreen mode

And then:

const token = localStorage.getItem("token");
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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",
    }
  );
}
Enter fullscreen mode Exit fullscreen mode

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");
}
Enter fullscreen mode Exit fullscreen mode

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
);
Enter fullscreen mode Exit fullscreen mode

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,
  };
}
Enter fullscreen mode Exit fullscreen mode

Notice what we return.

{
  "accessToken": "..."
}
Enter fullscreen mode Exit fullscreen mode

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,
  });
}
Enter fullscreen mode Exit fullscreen mode

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 });
  },
}));
Enter fullscreen mode Exit fullscreen mode

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,
});
Enter fullscreen mode Exit fullscreen mode

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;
});
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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);
  }
);
Enter fullscreen mode Exit fullscreen mode

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

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",
});
Enter fullscreen mode Exit fullscreen mode

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
Path Restrict where the cookie is sent

CORS configuration

import cors from "cors";

app.use(
  cors({
    origin: "https://app.peakiq.in",
    credentials: true,
  })
);
Enter fullscreen mode Exit fullscreen mode

Do not use a wildcard origin with credentialed requests.

Your frontend and backend deployment configuration must agree about cookie domain, SameSite, and HTTPS requirements.

CSRF protection

Because cookies are automatically sent by browsers, cookie-based authentication needs a CSRF strategy.

Depending on your deployment, use:

  • Strict origin validation
  • Appropriate SameSite settings
  • CSRF tokens for state-changing requests where required
  • Avoid state-changing GET requests

Do not assume HttpOnly prevents CSRF.

It protects cookie confidentiality from JavaScript, not the browser's automatic cookie sending behavior.


16. Logout Means Revoking the Session

A frontend logout that only clears Zustand is incomplete.

useAuthStore.getState().setAccessToken(null);
Enter fullscreen mode Exit fullscreen mode

That removes the access token from memory, but the refresh session may still be active.

The backend should revoke the session and clear the cookie.

export async function logout(req: Request, res: Response) {
  const refreshToken = req.cookies.refreshToken;

  if (refreshToken) {
    const hash = hashRefreshToken(refreshToken);

    await AuthSession.updateOne(
      {
        refreshTokenHash: hash,
      },
      {
        $set: {
          revokedAt: new Date(),
        },
      }
    );
  }

  res.clearCookie("refreshToken", {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "strict",
    path: "/api/auth",
  });

  return res.status(204).send();
}
Enter fullscreen mode Exit fullscreen mode

Then clear frontend state:

await api.post("/api/auth/logout");

useAuthStore.getState().setAccessToken(null);
Enter fullscreen mode Exit fullscreen mode

This creates a real logout.

The refresh session is no longer valid, and the browser cookie is cleared.

For a production application, users should also be able to see and revoke their active sessions from their account security page.


17. Modular Monolith Architecture

Authentication should not be mixed into controllers and utility files randomly.

Keep it inside a dedicated module.

src/
├── modules/
│   ├── auth/
│   │   ├── auth.controller.ts
│   │   ├── auth.service.ts
│   │   ├── auth.routes.ts
│   │   ├── auth.validation.ts
│   │   ├── auth.middleware.ts
│   │   ├── session.service.ts
│   │   └── auth.types.ts
│   │
│   ├── users/
│   │   ├── user.controller.ts
│   │   ├── user.service.ts
│   │   ├── user.model.ts
│   │   └── user.routes.ts
│   │
│   └── projects/
│       ├── project.controller.ts
│       ├── project.service.ts
│       ├── project.model.ts
│       └── project.routes.ts
│
├── middleware/
│   ├── error-handler.ts
│   ├── rate-limit.ts
│   └── validation.ts
│
├── utils/
│   ├── jwt.ts
│   ├── crypto.ts
│   └── logger.ts
│
├── config/
│   ├── database.ts
│   ├── cors.ts
│   └── environment.ts
│
└── app.ts
Enter fullscreen mode Exit fullscreen mode

The auth module owns authentication.

The user module owns user data.

The middleware layer owns reusable request behavior.

This structure is easier to test, audit, and maintain.


18. MongoDB Indexes That Matter

Authentication queries should not become slow as sessions grow.

At minimum, consider indexes for:

authSessionSchema.index(
  { refreshTokenHash: 1 },
  { unique: true }
);

authSessionSchema.index({
  userId: 1,
  revokedAt: 1,
});

authSessionSchema.index(
  { expiresAt: 1 },
  { expireAfterSeconds: 0 }
);
Enter fullscreen mode Exit fullscreen mode

These support:

  • Refresh token lookup
  • Session management by user
  • Cleanup of expired session records

Do not rely only on TTL cleanup to validate sessions.

Every refresh operation must explicitly verify expiration and revocation.


19. Scaling Authentication

You do not need microservices to build secure authentication.

A modular monolith is usually enough to start.

Phase 1 — MVP

  • Login and registration
  • Short-lived access tokens
  • Refresh sessions
  • HttpOnly cookies
  • Logout
  • Rate limiting
  • Password hashing

Phase 2 — Production Traction

  • Device sessions
  • Refresh token rotation
  • Session revocation
  • Reuse detection
  • Security audit logs
  • Multi-tab coordination
  • Email verification
  • Password reset

Phase 3 — Scale

  • Centralized session management
  • Redis for distributed coordination if needed
  • Dedicated security monitoring
  • Risk-based authentication
  • MFA
  • Suspicious login detection
  • Session policy enforcement

The architecture should evolve based on actual traffic and security requirements.


20. Authentication Gotchas

These are the mistakes I would watch closely during implementation.

1. HttpOnly does not prevent XSS

It prevents JavaScript from reading the cookie.

XSS can still perform actions as the authenticated user.

2. Refresh rotation creates race conditions

Multiple refresh requests can invalidate each other if the backend uses strict single-token rotation.

3. Never return refresh tokens in JSON

Use protected cookies instead.

4. Access tokens and refresh tokens should have different purposes

Use different secrets or signing keys if JWTs are used for both, and validate token type, issuer, audience, and expiration.

5. Logout should revoke server-side state

Clearing frontend memory alone is not enough.

6. Cookies require CSRF consideration

HttpOnly is not a CSRF defense.

7. Never log tokens

Avoid logging:

  • Authorization headers
  • Refresh cookies
  • Passwords
  • Authentication request bodies

8. A JWT is not a complete session management system

You still need to manage the session lifecycle.


21. Before Calling Authentication Production-Ready

Here is the checklist I would use before shipping.

  • [ ] Passwords are hashed with a suitable password hashing algorithm
  • [ ] Access tokens are short-lived
  • [ ] Refresh tokens are securely generated
  • [ ] Refresh tokens are hashed before database storage
  • [ ] Refresh token rotation is implemented
  • [ ] Refresh reuse detection is considered
  • [ ] Session revocation is implemented
  • [ ] Logout revokes the server session
  • [ ] Refresh cookie uses HttpOnly
  • [ ] Secure cookies are enabled in production
  • [ ] SameSite policy is explicitly configured
  • [ ] CORS uses an explicit origin allowlist
  • [ ] CSRF protections are in place
  • [ ] Login and refresh endpoints are rate-limited
  • [ ] Concurrent refresh requests are handled
  • [ ] Token secrets are not committed to source control
  • [ ] Tokens are never logged
  • [ ] Session expiration is validated server-side
  • [ ] Authentication failures do not leak sensitive information

Conclusion

JWT authentication is easy to implement.

Secure JWT authentication is much harder.

The difference between a tutorial implementation and a production implementation is not the JWT library. It is how you handle the entire session lifecycle.

A production MERN authentication system needs to think about:

  • Token security
  • Refresh rotation
  • Session persistence
  • Concurrent requests
  • Device management
  • Revocation
  • Cookie security
  • CSRF
  • XSS
  • Scalability

The biggest mistake is treating authentication as a login endpoint.

Authentication is a lifecycle.

If you design that lifecycle correctly from the beginning, your application becomes safer, easier to maintain, and much more predictable as it grows.

Top comments (0)