When does session property (express session data object) gets added to request object when using express-session middleware?

Viewed 222

When I use express-session middleware, when does the session property in request object(request.session) gets available?

  1. Does it always stay available since the beginning when the server starts? when no session is made (no login) then session data is empty but session property itself is always available on request object. Is is this case? OR
  2. does session object gets attached to request only when someone logs in? and when no user is logged in then request.session is always undefined . is it this?

The intention of this question is to know which, in typescript, out of the follow two type definition I have to use: (one is using session? and in another session is used)

import { SessionData } from "express-session";

declare module "express-session" {
  interface SessionData {
    userId: string;
  }
}
export interface MyContext {
  session: SessionData;
}

OR

import { SessionData } from "express-session";

declare module "express-session" {
  interface SessionData {
    userId: string;
  }
}
export interface MyContext {
  session?: SessionData;
}
1 Answers

After long waiting I got the answer in Ben Awad discord channel. Here it is

Session middleware is always defined, if no session exists on the request it'll return an empty object.

So the option-1 type definition is right, i.e.,

import { SessionData } from "express-session";

declare module "express-session" {
  interface SessionData {
    userId: string;
  }
}
export interface MyContext {
  session: SessionData;
} 
Related