I am building a full stack app using ExpressJS for the backend and Next.js for the frontend. The app is working fine when running locally on localhost. When I try to deploy on Vercel, it doesn't store cookies on the browser. It already sends cookies successfully from the backend
I have tried setting domain in the res.cookie but it didn't work
import axios from "axios";
export const apiRequest = axios.create({
baseURL: `${process.env.NEXT_PUBLIC_API_URL}/api`,
withCredentials: true,
// credentials: 'include',
// headers: {
// 'Content-Type': 'application/json',
// },
})
const res = await apiRequest.post("/auth/login", {
username,
password,
});
import express from 'express';
import dotenv from "dotenv";
import postRoutes from "../routes/post.route.js";
import userRoutes from "../routes/user.route.js";
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/posts", postRoutes);
app.use("/api/users", userRoutes);
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;
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 bcryptpare(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";
res.cookie(
"token",
token, {
httpOnly: true,
secure: isProduction,
sameSite: isProduction ? "none" : "lax",
path: "/",
// domain: isProduction ? '.vercel.app' : ".localhost",
partitioned: true,
maxAge: age,
}
);
return res.status(200).json({ message: "Login successful", data: userInfo });
} catch (err) {
console.log(err)
return res.status(500).json({ message: "Failed to login" })
}
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744253005a4565256.html
评论列表(0条)