Hello I am working on a Express server which send cookies from backend to the frontend browser and uses that cookies for route protection.
The problem that I am encountering is, when I am trying to send login or signup request from frontend to a deployed backend server on render it is not sending or saving (I don’t what’s the case) cookies on browser.
The frontend is on localhost while the backend is on render.
Below are the code snippets.
frontend login code
// import React from "react";
import { Link } from "react-router-dom";
import axios from "axios";
import toast from "react-hot-toast";
import { useNavigate } from "react-router-dom";
import { useContext } from "react";
import { UserContext } from "../../context/UserContext";
// import echo1 from "../../assets/echo1.jpeg";
import loginImg from "../../assets/login.png";
const LoginPage = () => {
const { setUserInfo } = useContext(UserContext);
const navigate = useNavigate();
const loginUser = async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const data = Object.fromEntries(formData);
console.log("Form Data:", formData, "Data:", data);
let response;
try {
response = await axios.post(
"https://render-location/auth/login",
{
email: formData.get("email"),
password: formData.get("password"),
},
{ withCredentials: true, credentials: true }
);
} catch (error) {
if (error.response) {
response = error.response;
toast.error(response.data.error);
}
}
console.log("Login Response:", response);
if (response.status === 200 && response.data?.email != null) {
setUserInfo(response?.data);
window.location.reload();
toast.success("Login Successful");
} else {
toast.error(response.data.error); // You can handle other cases accordingly
}
};
return (
<div className="grid grid-cols-2 h-[600px]">
<div className="col-span-1">
<img
src={loginImg}
alt="background"
className=" w-full h-full object-cover"
/>
</div>
<div className="p-8 flex items-center justify-center">
<div className="w-full max-w-md p-6 rounded-lg bg-white border">
<h1 className="text-2xl font-bold mb-6 text-gray-800">Login</h1>
<form className="space-y-4" onSubmit={loginUser}>
<div>
<label className="block text-sm font-medium text-gray-600">
Email
</label>
<input
type="text"
name="email"
placeholder="Enter your email"
autoComplete="current-email"
className="mt-1 p-2 w-full border border-gray-300 rounded-md focus:outline-none focus:border-2 focus:border-blue-500"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-600">
Password
</label>
<input
type="password"
name="password"
placeholder="Enter your password"
autoComplete="current-password"
className="mt-1 p-2 w-full border border-gray-300 rounded-md focus:outline-none focus:border-2 focus:border-blue-500"
/>
</div>
<button
type="submit"
className="w-full bg-blue-500 text-white rounded-md p-2 hover:bg-blue-600 focus:outline-none focus:ring focus:border-blue-700"
>
Login
</button>
<hr className="my-4 border-gray-300" />
<div className="flex gap-2">
{/* <Link className='text-blue-500 hover:underline'>Forgot Password?</Link> */}
<span> Don't have an account?</span>
<Link to="/register" className="text-blue-500 hover:underline">
Create an Account
</Link>
</div>
</form>
</div>
</div>
</div>
);
};
export default LoginPage;
backend jwt generator code
const jwt = require("jsonwebtoken");
const generatetoken = (id, res) => {
const token = jwt.sign({ id }, process.env.JWT_SECRET, {
expiresIn: "7d",
});
res.cookie("jwt", token, {
httpOnly: true,
secure: true,
sameSite: "None",
maxAge: 7 * 24 * 60 * 60 * 1000,
});
};
module.exports = { generatetoken };
Backend server code:
const express = require("express");
const dotenv = require("dotenv");
const connectDB = require("./DB");
const path = require("path");
const Queryrouter = require("../Routes/Query.routes");
const Summaryrouter = require("../Routes/Summarizer.routes");
const Authrouter = require("../Routes/Auth.routes");
const cookieParser = require("cookie-parser");
const cors = require("cors");
//configurations
dotenv.config();
const app = express();
//middlewares
app.use(express.json());
app.use(cookieParser());
app.use(
cors({
origin: [
"http://localhost:5173",
"http://localhost:3000",
],
methods: ["GET", "POST", "PUT", "DELETE", "PATCH"],
credentials: true,
})
);
//connect to server and database
const PORT = process.env.PORT || 5000;
const startserver = async () => {
await connectDB();
try {
app.listen(PORT, () => {
console.log(`server listening on http://localhost:${PORT}`);
});
} catch (error) {
console.log(error.message);
}
};
//routes
app.use("/api", Queryrouter);
app.use("/summary", Summaryrouter);
app.use("/auth", Authrouter);
app.get("/working", (req, res) => {
res.send("API is running");
});
module.exports = startserver;
The application works fine as intended on local backend server and I am receiving jwt token in cookies as intended but its not working at all on the deployed server even after doing all the necessary configurations required for cookies on a deployed server.