Unable to set a cookie using express-session wiht nestjs and graphql

13 views Asked by At

I've been learning nestJS and implemented a small project that will allow users to login and on the server side store user details. However, when i try to store userID i get the following error:

[Nest] 79776  - 03/06/2024, 12:56:03 AM   ERROR [ExceptionsHandler] Cannot set properties of undefined (setting 'userId')
TypeError: Cannot set properties of undefined (setting 'userId')

My login resolver is as follows:

  @Mutation(() => UserClass, { nullable: true })
  async login(
    @Args('loginInput') loginInput: UserInput,
    @Context() context: UserContext,
  ) {
    const user = await this.userService.login(loginInput);

    // Ensure that context.req.session is defined before setting userId
    context.req.session.userId = user.id;

    return user;
  }

And my main.ts file is setup in this way:

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
  );

  await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
    transport: Transport.REDIS,
    options: {
      host: 'localhost',
      port: 6379,
    },
  });

  const store = new RedisStore({
    client: redis as any,
    prefix: 'pinnaclftxweb',
  });

  app.use(
    session({
      genid(req) {
        return v4();
      },
      store,
      name: 'qid',
      secret: 'aslkdfjoiq12312', //place on enviroment file
      resave: false,
      saveUninitialized: false,
      cookie: {
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        maxAge: 1000 * 60 * 60 * 24 * 7 * 365, // 7 years
      },
    }),
  );
  await app.listen(3000);
}
bootstrap();

I really do not understand what i could be doing wrong, please help

0

There are 0 answers