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"
)
);
π΄ Issue:
I had secure: true
when 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",
};
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)