expresssession-variables

Express.js not saving session data


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?


Solution

  • To close out this question with the answer, you can change this:

    app.use(express.static("public"));
    

    to this:

    app.use(express.static("public"), {index: false});
    

    The problem was that express.static() was "stealing" the / route (because it found an index.html file in its directory and thus the route handler that was supposed to run for that route and then execute this line of code was never being executed:

    req.session.userId = "user-" + utils.generateRandomString()
    

    So, it wasn't an issue of losing the cookie or the session. It was an issue of the desired route handler was never executing so the userId value was never set in the session in the first place.