Search code examples
expresssessionexpress-session

express-session: session is not accessable in other routes


I'm using express-session to store auth token in the session. The problem i'm facing is that the session i set in the /authenticate (post route) is not undefined in the /join (get route). I have searched for the similar questions but that didn't help. Any idea what's going wrong in my code?

server.js

// All required modules loaded..

// Session config
app.use(
  session({
    secret: "mysessionsecret",
    resave: false,
    saveUninitialized: false,
    cookie: { secure: false, maxAge: 6000000 }
  })
);

// @route:authenticate
app.post("/authenticate", async (req, res) => {
  const { username, password } = req.body;

  try {
    const user = await User.findOne({ username });

    if (!user) {
      return res.status(400).json({ msg: "Invalid username entered" });
    }

    // Compare the password
    const compare = await bcrypt.compare(password, user.password);

    if (!compare) {
      return res.status(400).json({ msg: "Incorrect password" });
    }

    // Create token of the user ID
    jwt.sign(
      {
        userId: user.id
      },
      config.get("jwtSecret"),
      {
        expiresIn: "2d"
      },
      (err, token) => {
        if (err) throw err;

        if (!req.session.user_id) {
           req.session.token = token;

           console.log(req.session.token); // Accessable here
        }
      }
    );

    res.end();
  } catch (error) {
    return res.send("Server error");
  }
});



   // @route:get /join
   app.get("/join", (req, res) => {
    console.log(req.session.token); // token not accessable here. returns undefined

     return res.end();
   });

Solution

  • The token will not be in the cookie, that's on the server only. The cookie is just a session ID. The default name for the express-session cookie is connect.sid. There should be a cookie with that name.

    If you don't see that cookie anywhere, try saveUninitialized:true. You may also try calling req.session.save() after you modify the session in your /authenticate route. Either one of those should cause the session cookie to get set.

    When you set saveUnitialized: false, you tell express-session NOT to set your session cookie until you tell it to. Unfortunately, the doc doesn't really say how you tell it to now set the session cookie. My guess was that req.session.save() might do it or just turning saveUnitialized to true would also do it. You can experiment with only using one of the two changes, though now you have a session cookie so you'd have to clear it in order to test with just one of them.