I am facing an issue where my backend, deployed on AWS, cannot properly handle cookies for authentication. Here’s the scenario:
Setup:
I used cookie-parser to generate and set a JWT token in a cookie using res.cookie on the backend.
Locally, everything works perfectly:
I can log in.
All API requests after login work as expected.
Problem:
After deploying the backend on AWS and connecting it to my frontend:
I can log in successfully, and the token seems to be generated and sent.
However, subsequent API requests are forbidden (403), indicating that the backend cannot read the cookie sent by the browser.
The issue only occurs in the deployed environment; everything works fine locally.
Assumptions:
I suspect the deployed backend on AWS cannot access the cookie sent by the browser.
export const fetchUser = createAsyncThunk(
"auth/fetchUserProfile",
async (_, { rejectWithValue }) => {
try {
const response = await axios.get(`${BACKEND_API}/api/user/myprofile`, {
withCredentials: true,
});
return response.data;
} catch (error: any) {
return rejectWithValue(error.response?.data);
}
}
);
import jwt from "jsonwebtoken";
const generateToken = (id, res) => {
const token = jwt.sign({ id }, process.env.JWT_SEC, {
expiresIn: "15d",
});
res.cookie("token", token, {
maxAge: 15 * 24 * 60 * 60 * 1000,
httpOnly: true,
sameSite: "none",
secure: true,
});
};
export default generateToken;
What I’ve Tried:
Ensured sameSite: “none” and secure: true are set in res.cookie.
Confirmed that the backend is served over HTTPS.
Tested locally (everything works fine).
Expected Behavior:
Environment Details:
Backend: Node.js with Express.js.
Hosted on: AWS (EC2 instance).
Frontend: React.js.
Backend is served over: HTTPS.
After login, the token should be stored in the cookie.
Subsequent API requests should include the cookie, allowing the backend to authenticate the user.
Actual Behavior:
The login works, but the cookie is not being sent back to the backend for other API requests in the deployed environment.
Question:
Why is the cookie not accessible to the backend when deployed on AWS, and how can I fix this issue?
The best way is that the Cookies can be set from the server side. Cookies more Structurely backend developer can set from the server side. when user logged in token automatically set in the browser cookies. other try you can go with defining the domine name as a parameter while setting the cookies or you can go with local storage. Finally very advanced way is that you have to use the different storage type in production level.