i am building a full stack web app using expressJS for the backend and NextJS for the frontend. I have built the /login endpoint and it's working fine locally. However, it didn't work after I deployed it on vercel.
The problem is that I send a cookie from the backend and it's working fine but it's not stored in the browser after deployment. It's working fine on localhost.
export const login = async (req, res) => { try { const { username, password } = req.body;
// Check user exists const user = await prisma.user.findUnique({ where: { username } }); if (!user) return res.status(401).json({ message: "Invalid credentials" });
// Check correct password const isValidPassword = await bcrypt.compare(password, user.password); if (!isValidPassword) return res.status(401).json({ message: "Invalid credentials" });
// Generate a cookie tooken const age = 1000 * 60 * 60 * 24 * 7; // 7 days
const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, { expiresIn: age }); const { password: password_, ...userInfo } = user; const isProduction = process.env.NODE_ENV === "production";
return res.cookie( "token", token, { httpOnly: true, secure: isProduction, sameSite: isProduction ? "none" : "lax", path: "/", // domain: isProduction ? '.vercel.app' : ".localhost", partitioned: isProduction, maxAge: age, } ).json({ message: "Login successful", data: userInfo });
} catch (err) { console.log(err) return res.status(500).json({ message: "Failed to login" }) }}// api/index.js import express from 'express';import dotenv from "dotenv";import authRoutes from "../routes/auth.route.js";import cookieParser from 'cookie-parser';import cors from "cors";const port = process.env.PORT || 4000;dotenv.config()
const app = express();app.set('trust proxy', 1);app.use(cors({ origin: process.env.CLIENT_URL, credentials: true,}))app.use(express.json());app.use(cookieParser());app.use("/api/auth", authRoutes);
app.get("/", (req, res) => { return res.send("It works");})app.use((_err, _req, res, _next) => { res.status(500).json({ status: 'Failed', message: 'Something went wrong', });});
app.listen(port, () => console.log(`server running at ${port}`));
export default app;// axios configimport axios from "axios";export const apiRequest = axios.create({ baseURL: `${process.env.NEXT_PUBLIC_API_URL}/api`, withCredentials: true,})// frontenedconst res = await apiRequest.post("/auth/login", { username, password, });


