🛠️ Fixing "Invalid Access Token" Issue in MERN Authentication
Prathviraj H

Prathviraj H @prathvihan108

About: 🚀 A Passionate Web Developer | Building Scalable & Dynamic Applications 💻 Full-stack developer exploring React, Node.js, and AI-powered projects. Constantly learning and sharing insights on web dev

Joined:
Feb 11, 2025

🛠️ Fixing "Invalid Access Token" Issue in MERN Authentication

Publish Date: Mar 8
0 0

The Issue

While working on authentication in my MERN stack project, I faced a strange bug:

✅ Access token was successfully sent to the frontend.
❌ But when making requests to protected routes, it showed "Invalid Access".

The Root Cause

The problem was in my cookie settings:

const options = {
    httpOnly: true, 
    secure: process.env.NODE_ENV === "production", 
    sameSite: process.env.NODE_ENV === "production" ? "None" : "Lax",
};

return res
    .status(200)
    .cookie("accessToken", accessToken, options)
    .cookie("refreshToken", refreshToken, options)
    .json(
      new ApiResponse(
        200,
        {
          user: loggedInUser,
          accessToken,
          refreshToken,
        },
        "user logged in successfully"
      )
    );

Enter fullscreen mode Exit fullscreen mode

🔴 Issue:

I had secure: truewhen NODE_ENV was "production", meaning cookies were only sent over HTTPS. But my frontend was running on HTTP (localhost:3000) during development, so the cookies were not being sent in requests.

The Fix

Here’s how to resolve it:

✅ Option 1: Disable secure for Development

const options = {
    httpOnly: true, 
    secure: process.env.NODE_ENV === "production" ? true : false,  // ❌ Only secure in production
    sameSite: process.env.NODE_ENV === "production" ? "None" : "Lax",
};

Enter fullscreen mode Exit fullscreen mode

Now, in development, secure: false allows cookies over HTTP.

✅ Option 2: Use HTTPS in Development

Alternatively, run your frontend on HTTPS by using a local HTTPS setup (e.g., with a self-signed certificate).

✅ Option 3: Use Postman for Testing

Since Postman doesn't care about secure cookies, it can help test API calls.

Key Takeaway

  • secure: true only works with HTTPS.
  • If your frontend runs on HTTP, set secure: false in development.
  • Using sameSite: "None" also requires secure: true, so be careful.

Have you faced similar issues? Let me know in the comments! 🚀

Comments 0 total

    Add comment