Reputation: 1310
I want to use client-sessions module with my Express backend. So I've installed the module and set it up to work with Express like this:
var sessions = require('client-sessions');
app.use(sessions({
cookieName: Constants.CLIENT_SESSION_NAME, // pi_client_session
secret: Constants.CLIENT_SESSION_SECRET, // some long string here
duration: Constants.CLIENT_SESSION_LIFETIME // 24 * 60 * 60 * 1000;
}));
But, for some reason, it's empty on every request. Here's the example:
router.get('/auth', function(req, res, next) {
console.log("CLIENT SESSION BEFORE: " + JSON.stringify(req[Constants.CLIENT_SESSION_NAME]));
req[Constants.CLIENT_SESSION_NAME].test = "saved";
console.log("CLIENT SESSION AFTER: " + JSON.stringify(req[Constants.CLIENT_SESSION_NAME]));
return res.json({ sessionSaved: true});
}
And here is the output I get everytime:
CLIENT SESSION BEFORE: {}
CLIENT SESSION AFTER: {"test":"saved"}
I've tried from Google Chrome, Opera. The same result.
My setup is like this: ReactJS app proxies from localhost:3000 to localhost:3001 which is my express backend. I've tried direct requests to express with Postman, and it saved the session normally. So the problem is definitely in Proxying from react to express and back. My package.json file on react's side is as follows (I didn't include dependencies):
"scripts": {
"build-css": "node-sass-chokidar src/ -o src/",
"watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",
"start-js": "react-scripts start",
"start": "npm-run-all -p watch-css start-js",
"build": "npm run build-css && react-scripts build",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:3001"
So the question is, how can I get client sessions using proxy like this?
Upvotes: 0
Views: 231
Reputation: 203554
Because your React app is running on a different origin than your backend, you need to explicitly tell fetch
to pass credentials (like cookies) with each request:
fetch('http://your-backend', {
credentials: 'include'
}).then(...)
Upvotes: 1