0

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?

12
  • This could be a client problem. What is making the 2nd request? Is it an Ajax call via Javascript? If so, it has to have the right settings so that it will send the session cookie. If it doesn't send the session cookie, then the next call will just make a new, empty session. Please show the relevant client code making this request. Commented Nov 12, 2023 at 5:30
  • Yes, it is an AJAX call. But the session cookie (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. Commented Nov 12, 2023 at 6:24
  • Please show the relevant client code. I see nothing wrong with the server code. Commented Nov 12, 2023 at 6:28
  • I've added the (minified) client code to the question. Commented Nov 12, 2023 at 6:37
  • You need the credentials: 'include' option with your fetch() so it will send the session cookie. See stackoverflow.com/questions/50698444/…. Commented Nov 12, 2023 at 6:44

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.