Nestjs session not saving

Viewed 379

I am new to nestjs and started my first application today. I am trying to implement user login using express-session and connect-mongo to persist sessions even if my docker container gets killed or replaced.

I have install express-session and connect-mongo and configured them in main.ts

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(
    session({
      secret: process.env.SECRET,
      resave: true,
      saveUninitialized: true,
      store: ConnectMongo.create({ mongoOptions: { useNewUrlParser: true, useUnifiedTopology: true }, mongoUrl: process.env.MONGO_URI, collectionName: 'loginsessions' }),
    }),
  );
  await app.listen(3000);
}

I have created a login service that returns the details to set in session uid and role

@Post('login')
  @HttpCode(HttpStatus.OK)
  async login(@_Session() session: Session, @Body() body: Pick<UsersDto, 'email' | 'password'>) {
    console.log(session.uid, session.role);
    if (session.uid) {
      return this.usersService.getId(session.uid);
    } else {
      const user = await this.usersService.login(body.email, body.password);
      session.uid = user._id;
      session.role = user.role;
      session.save();
      return { success: true, message: 'Logged in' };
    }
  }

Here are my two requests

$ curl -c cookie localhost:3000/users/login -XPOST -H "Content-Type: application/json" -d '{"email": "tbhaxor@gmail.com", "password": "test"}'  && echo
{"success":true,"message":"Logged in"}
$ curl -c cookie localhost:3000/users/login -XPOST -H "Content-Type: application/json" -d '{"email": "tbhaxor@gmail.com", "password": "test"}'  && echo
{"success":true,"message":"Logged in"}

In application, accessing session values give me undefined

enter image description here

Also in DB, no session property uid or role is set

enter image description here

0 Answers
Related