Cannot set property 'userId' of undefined in session variable

Viewed 248

Cannot read set property of 'userId' of undefined is a classic error that has been experienced in Express frameworks and documentation here covers what to do about it, but how do you resolve this issue in a NestJS application?

1 Answers

When you get an error message that says Cannot set property 'userId' of undefined you want to look at what is going on with your cookie-session.

Do you have a cookie-session installed?

The error is being thrown whenever you try to set the user id property on the users' session object, because that cookie middleware is not installed or it's not running, you get undefined.

So when you try to set a property on undefined, you get this classic error message.

So your cookie-session may not be set up.

Enough answers were given in a plain ExpressJS API, but what if you are working with NestJS? Well, here is the NestJS way to resolve this.

Import the following to your app.module.ts file:

import { Module, ValidationPipe } from '@nestjs/common';
import { APP_PIPE } from '@nestjs/core';

Go down to your list of providers and inside the array and a brand new object:

providers: [
    AppService,
    {
      provide: APP_PIPE,
      useValue: new ValidationPipe({
        whitelist: true,
      }),
    },
  ],

So what does this really do? It says whenever we create an instance of the app module, automatically make use of it. Apply it to every incoming request that flows to the application, run it through the instance of a class. That's how to set up a global pipe, but you have to set up the cookie session middleware into a global middleware.

You need to import the following to the same file:

import { MiddlewareConsumer, Module, ValidationPipe } from '@nestjs/common';

At the bottom, add the following:

export class AppModule {
  configure(consumer: MiddlewareConsumer) {}
}

The configure function gets called automatically whenever the application starts listening for incoming traffic. So inside of here I can set up some middleware that will run on every single incoming request.

To do, we call or reference consumer.apply() like so:

export class AppModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(
      cookieSession({
        keys: ['dfghjkl'],
      }),
    );
  }
}

I then need to ensure I add in a require statement for cookie session at the top:

const cookieSession = require('cookie-session');

And at the bottom also add:

export class AppModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(
        cookieSession({
          keys: ['dfghjkl'],
        }),
      )
      .forRoutes('*');
  }
}

That means that I want to make use of the middleware on every single incoming request that comes into the application. That should be it.

Related