I am working on a MERN project. I am trying to implement authentication system. But when running the server in localhost. The cookies are available in request headers but on runnning server on vercel or render. I am not getting the cookies in the header.
Frontend code :
export const getUser = () => {
return axios.get(`${domain}/api/users/details`, {
withCredentials: true,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Credentials": "true",
},
});
};
backend(controller)
const loginUser = AsyncHandler(async (req, res) => {
const { userName, password, email } = req.body;
if (!(userName || email))
throw new ApiError(400, "Username or email is required");
const user = await User.findOne({
$or: [{ userName }, { email }],
});
if (!user) throw new ApiError(400, "User not found ");
const isPasswordValid = await user.isPasswordCorrect(password);
if (!isPasswordValid) throw new ApiError(401, "Invalid user credentials");
const { refreshToken, accessToken } = await generateRefreshAndAccessToken(
user._id
);
const loggedInUser = await User.findById(user._id).select(
"-password -refreshToken"
);
const options = {
httpOnly: true,
secure: true,
sameSite: "None",
path: "/",
};
return res
.status(200)
.cookie("access-token", accessToken, options)
.cookie("refresh-token", refreshToken, options)
.json(
new ApiResponse(
200,
{ user: loggedInUser, accessToken, refreshToken },
"User logged in successfully"
)
);
});
Backend(middlewares):
export const verifyJWT = AsyncHandler(async (req, _, next) => {
try {
const token =
req.cookies?.["access-token"] ||
req.header("Authorization")?.replace("Bearer ", "");
if (!token) {
throw new ApiError(401, "Unauthorized request");
}
const decodedToken = jwt.verify(token, process.env.SECRET_KEY);
const user = await User.findById(decodedToken?._id).select(
"-password -refreshToken"
);
if (!user) {
throw new ApiError(401, "Invalid Access Token");
}
req.user = user;
next();
} catch (error) {
throw new ApiError(401, error?.message || "Invalid access token");
}
});
cors:
const allowedOrigins = [
"http://localhost:5173",
];
app.use(
cors({
credentials: true,
origin: (origin, callback) => {
if (allowedOrigins.includes(origin) || !origin) {
callback(null, true);
} else {
callback(new Error("Not allowed by CORS"));
}
},
})
);
Routes for getting user detail :
router.get("/details", verifyJWT, getCurrentUser);
New contributor
b1shwash is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.