Session: Express-session not working via Router

Created on 17 Jul 2020  路  3Comments  路  Source: expressjs/session

Hi,
This is my index.js file:

  • index.js
// Some code..

app.use(session({
    name : 'app.sid',
    secret: "1234567890QWERTY",
    resave: true,
    saveUninitialized: true
));

app.get("/test", (req, res) => {
    const sess = req.session;
    sess.hello = true;
    console.log(sess);
    res.send(`Session: ${sess.hello}); // Session: true
});

This works just fine, I can access the "req.session" object.
How ever, if I refactor the exact same code using express router, I cannot access "req.session"

  • Index.js:
// Some code..
const { testRoute } = require("./test-route");

app.use(session({
    name : 'app.sid',
    secret: "1234567890QWERTY",
    resave: true,
    saveUninitialized: true
));

app.use(testRoute);
});
  • test-route.js:
const express = require("express");
const router = express.Router();

router.get("/test", (req, res) => {
    const sess = req.session;
    sess.hello = true;
    res.send(`Session: ${sess.hello}); // Session: undefined
});

exports.testRoute = router;

Using "express" version 4.17 and "express-session" 1.17.1, thanks!

awaiting more info question

All 3 comments

@pixarfilmz112 If you are leaving path unset it will default to "/" and so you should be able to use a router as you have suggested. Please provide a minimal and complete example of the issue you are having. This is most likely an issue with your application code.

I am closing this Issue @pixarfilmz112. I think you may have found the issue in your code. I will of course immediately reopen this upon request.

I am closing this Issue @pixarfilmz112. I think you may have found the issue in your code. I will of course immediately reopen this upon request.

Sorry, forgot to answer. The problem was that I declared app.use(someRoute) before app.use(session(...)). I needed to swap them.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

aheyer picture aheyer  路  15Comments

rukshn picture rukshn  路  20Comments

alex55132 picture alex55132  路  22Comments

skoranga picture skoranga  路  30Comments

G-Adams picture G-Adams  路  16Comments