I am building a web app and I would like to assign every client a random user ID (which should be retained across sessions). For this, I am setting the userId session variable.
const app = express()
app.use(session({
secret: '1234',
resave: true,
saveUninitialized: true,
}))
app.use(cors())
app.use(express.json())
app.use(express.urlencoded())
app.use(express.static("public"))
app.get("/", (req, res) => {
req.session.userId = "user-" + utils.generateRandomString()
res.sendFile(__dirname + '/index.html')
})
app.post("/api/auth", (req, res) => {
console.log(req.session)
// auth logic
res.send("Success")
})
So when the user navigates to /, the userId is set. This userId should be sent with the next request, to /api/auth, But the userId session variable is always undefined. This is what the console.log call prints:
Session {
cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true }
}
Edit: here is the minimal client code that results in the problem:
fetch("/api/auth", {
method: "POST",
body: ""
}).then(res => res.text().then(text => console.log(text)))
I tried changing the order of the session middleware (placing it after cors, json, urlencoded and static) but to no avail.
So, how do I get around this?
connect.sid) is included in the request, and I can see it in the browser's dev tools. The problem is probably in the server - it is not able to find the session with the given session ID.credentials: 'include'option with yourfetch()so it will send the session cookie. See stackoverflow.com/questions/50698444/….