I worked on a MERN project and everything was going well in development(local) mode. When i hosted my code on vercel i noticed that session are not working properly. my mentor suggested to create a small app to debug the issue so i created the following one. It is meant to store a value and returns it in the next ‘/get’ call?
const express = require('express');
const app = express();
const cors = require('cors');
const session = require('express-session');
const bodyParser = require('body-parser');
const MongoDBStore = require('connect-mongodb-session')(session);
app.use(cors({
origin: 'my_domain',
credentials: true
}));
var store = new MongoDBStore({
uri: "my_atlas_uri?retryWrites=true&w=majority",
collection: 'mySessions',
});
app.use(
session({
secret: "Session_Key",
resave: true,
store: store,
saveUninitialized: false,
cookie: {
httpOnly: true,
sameSite: true,
secure: true,
maxAge: 6 * 60 * 60 * 1000, //6 hours
rolling: true,
},
})
);
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.json('hello world');
});
app.get('/store', (req, res) => {
req.session.store = 'hi0';
req.session.save(err => {
if(err) {
console.log(err);
}
console.log(req.session.store,"hlo");
res.json('stored');
});
});
app.get('/get', (req, res) => {
console.log(req.session.store);
res.json({data:req.session.store,id:req.sessionID,id1:req.session.id,cookie:req.session.cookie});
});
so it is returnig empty on req.session.store. the data(cookie) is being stored in my mongodb database. the staus code for “/store” is 304 and for “/get” is 200. i am deploying on vercel
this is my vercel.json
{
"version": 2,
"builds": [
{ "src": "*.js", "use": "@vercel/node" }
],
"routes": [
{ "src": "/(.*)", "dest": "/"}
]
}
Vishnu Shouryan Reddy Hanmandl is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.