I recently deployed my first MERN project (Blog web app) on Vercel and I’m facing an issue where cookies are not being stored on the client side, leading to session expiration and forced logouts.
The problem occurs after a successful login. I store the user data and set auth = true
in the session. The login works, and I’m able to store the session on the server, but when trying to access protected routes, I get a “Session Expired, Please Login” toast because my session data (auth
) is undefined. I believe the issue is that the cookie isn’t sent along with the request, resulting in the missing session and expired state.
Here’s the current setup:
RTK Query (Client-Side):
baseQuery: fetchBaseQuery({
baseUrl: "https://my-api-url.com",
credentials: 'include'
})
index.js (Server-Side CORS and Session Configuration):
app.use(cors({
origin: 'https://my-client-side.vercel.app',
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true
}));
app.use(
session({
secret: process.env.SECRET_KEY,
resave: false,
saveUninitialized: false,
store: store,
cookie: {
httpOnly: true,
secure: true,
sameSite: "none",
maxAge: 1000 * 60 * 60 * 24, // 24 hours
path: "/",
domain: process.env.COOKIE_DOMAIN // e.g., '.mydomain.com'
}
})
);
vercel.json
{
"version": 2,
"builds": [
{
"src": "index.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "index.js",
"methods": ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
"headers": {
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Origin": "https://my-client-side.vercel.app",
"Access-Control-Allow-Methods": "GET,OPTIONS,PATCH,DELETE,POST,PUT",
"Access-Control-Allow-Headers": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, Authorization"
}
}
]
}
I tried changing the values of the keys present in session middleware with different values.
I added samesite = process.env.NODE_ENV=’production’ in session middleware
I added all the env variables on vercel
Changed config on vercel.json file
I’m using React Quill in my app, and during development, blog images were uploaded with URLs pointing to http://localhost:8000. After deploying, the images still pointed to localhost, causing a “Mixed Content” warning since my app now uses HTTPS, but the images were being fetched over HTTP.
I fixed this by updating the image URLs to HTTPS, but I’m not sure if there are any additional steps or settings needed in Vercel to prevent similar issues.
I’m stuck from past two day.
Any guidance or suggestions would be greatly appreciated!
muskan dodmani is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.