nest-middlewares icon indicating copy to clipboard operation
nest-middlewares copied to clipboard

[express-session] Can't keep session values with default options.

Open monaka opened this issue 6 years ago • 7 comments

In @nest-middlewares/express-session, always new session object is created per routing when options was applied.

https://github.com/wbhob/nest-middlewares/blob/077baf8296b61684b273d9c8689d985186669ba6/packages/express-session/index.ts#L15-L16

And express-session creates new instance of MemorySession if option.store wasn't specified.

https://github.com/expressjs/session/blob/10607bdb780204b91a8cf90e4ce27726619b8285/index.js#L99-L100

So the app can't keep values in the session.

I suspect the value of expressSession should be cached in the class ExpressSessionMiddleware.

monaka avatar Sep 12 '19 07:09 monaka

Workaround for now: setting sessionStore explicitly. Like

export class ApiModule {
  private sessionStore = new MemoryStore();

  configure(consumer: MiddlewareConsumer) {
    ExpressSessionMiddleware.configure({
      store: this.sessionStore,

monaka avatar Sep 12 '19 07:09 monaka

can you open a PR? I didn't know it worked like this. I'd be happy to merge

wbhob avatar Sep 12 '19 15:09 wbhob

I had the same problem, I have the same problem. Each session cannot be saved

my code

     ExpressSessionMiddleware.configure({
      secret: 'liubf', 
      name: 'nest',
      resave: false,
      saveUninitialized: false, 
      rolling: true, 
      cookie: {
        maxAge: 60 * 1000 * 30, 
      },
    });

ShareQiu1994 avatar Feb 01 '20 08:02 ShareQiu1994

(QJZO(29PN2XU8UG{40)%KU

ShareQiu1994 avatar Feb 01 '20 08:02 ShareQiu1994

I'd be glad to accept a PR for this issue

wbhob avatar Feb 03 '20 20:02 wbhob

export class ExpressSessionMiddleware implements NestMiddleware {

    // DELETE THESE LINES IF MIDDLEWARE DOES NOT TAKE OPTIONS
    public static configure(opts: expressSession.SessionOptions) {
        this.options = opts;
    }

    private static options: expressSession.SessionOptions;
    private handler: Express.RequestHandler;
    
    private getHandler() {
        if (this.handler) return this.handler;
        if (ExpressSessionMiddleware.options) this.handler = expressSession(ExpressSessionMiddleware.options);
        else this.handler = expressSession();
        return this.handler;
    }

    public use(req: any, res: any, next: any) {
        this.getHandler()(req, res, next);
    }
}

Seems modify the function to singleton will work I am fine to make a pr for this changes

vip30 avatar Jul 15 '20 13:07 vip30

Fixed in 10.0.1

wbhob avatar Oct 27 '23 09:10 wbhob