Search code examples
node.jstypescriptsessionredisexpress-session

Express-session store is not returning the full session object with custom data


I've been working on this problem for a while, and I am stumped.

I am using express-session with connect-redis as a store for the sessions. I am using typescript.

I added this to the top of my server file and I am able to access the fields without any typescript errors.

declare module "express-session" {
  interface SessionData {
    userId: string;
    role: UserRole;
  }
}

When I log a user in, I set the extra SessionData fields.

request.session.userId = user._id.toHexString();
request.session.role = user.role;

console.log(request.session);

Via Postman, I can see that the cookie is set and returned. Additionally, I checked Redis for the session key and the session is correct. e.g.

{\"cookie\":{\"originalMaxAge\":604800000,\"expires\":\"2023-01-23T17:34:05.158Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"},\"userId\":\"1234\",\"role\":\"userRole\"}

However, the extra fields I added to SessionData are not being populated after calling the session middleware. Instead of getting:

Session {
  cookie: {
    path: '/',
    _expires: 2023-01-23T17:52:49.153Z,
    originalMaxAge: 604800000,
    httpOnly: true,
    secure: true
  },
  userId: '1234',
  role: 'userRole'
}

I get:

Session {
  cookie: {
    path: '/',
    _expires: 2023-01-23T17:52:52.339Z,
    originalMaxAge: 604800000,
    httpOnly: true,
    secure: true
  }
}

This is how I am calling the session middleware:

const sessionOptions: SessionOptions = {
  secret: "secret key",
  resave: true,
  saveUninitialized: true,
  cookie: { secure: true, httpOnly: true },
  store: store,
};
app.use(session(sessionOptions));

I thought it may have been an issue with redis, but the key/value is being persisted. I thought maybe it was an issue with connect-redis, so I used the default MemoryStore, but that doesn't work either.

Any help would be appreciated!


Solution

  • Of course right after I ask this question I figure out what the answer is...

    First, don't manually set the cookie for the session id in the response. It will automatically be done for you.

    Second, ensure that secure is FALSE on localhost.