DEV Community

Prathviraj H
Prathviraj H

Posted on

πŸ› οΈ Fixing "Invalid Access Token" Issue in MERN Authentication

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! πŸš€

Top comments (0)