user7496931
user7496931

Reputation: 1519

Session from express-session not persisting through requests

I'm using express-session and trying to implement a protected route with custom middleware.

[NOTE: I'm currently storing my session in-memory]

app.use(
  session({
    secret: "f4z4gs$Gcg",
    cookie: { maxAge: 300000000, secure: true },
    saveUninitialized: false,
    resave: false,
    store,
  })
);

// MIDDLEWARE
function ensureAuthenticated(req, res, next) {
  console.log(req.session) //  This doesn't show the user and authenticated properties created in the POST login request
  if (req.session.authenticated) {
    return next();
  } else {
    res.status(403).json({ msg: "You're not authorized to view this page" });
  }
};

app.post("/login", (req, res) => {
  const { username, password } = req.body;

  db.users.findByUsername(username, (err, user) => {
    if (user) {
      if (user.password === password) {
        // Add your authenticated property below:
        req.session.authenticated = true;
        // Add the user object below:
        req.session.user = {
          username,
          password,
        };
        // Send the session back to the client below:
        res.json(req.session); // Properties show up here
      } else {
        res.status(403).json({ msg: "Bad Credentials" });
      }
    } else {
      res.status(403).json({ msg: "No user found!" });
    }
  });
});


// PROTECTED ROUTE
app.get("/protected", ensureAuthenticated, (req, res) => {
  res.render("profile");
});

Once a user logs in successfully, I try to add two properties into req.session: authenticated and the user object. However, once I login and try to access /protected with the middleware, my session properties do not persist (no user or authenticated property). Am I missing something?

Upvotes: 1

Views: 133

Answers (1)

Tejas_hooray
Tejas_hooray

Reputation: 636

Try setting secure to false in the cookie object. If you want it to be httpOnly, then just set httpOnly to true.

Upvotes: 1

Related Questions