node.jscookiesnestjsexpress-sessions

Express-session: not resetting cookie expiration on each request


I'm using express-session to implement authentication in my web application. However, I'm encountering an issue where the cookie expiration time is not getting reset on each request. Below is the code I'm using:

main.ts file:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as session from 'express-session';
import * as cookieParser from 'cookie-parser';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(cookieParser());
  app.use(
    session({
      secret: process.env.COOKIE_SECRET,
      resave: false,
      saveUninitialized: true,
      cookie: { maxAge: 60000 } // 1 minute
    }),
  );
  await app.listen(process.env.PORT ? parseInt(process.env.PORT) : 3000);
}
bootstrap();

auth.controller.ts file:

import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
import { Req, HttpStatus, HttpException } from '@nestjs/common';

@Post('login')
logIn(@Body() createAuthDto, @Req() request) {
  request.session.User = {
    website: 'hello',
    type: 'blog hello',
    like: '4550'
  };
  return new HttpException('OK', HttpStatus.OK);
}

@Get('authenticated')
authenticated(@Body() createAuthDto) {
  if (request.session.User) {
    return new HttpException('OK', HttpStatus.OK);
  }
  return new HttpException('No session', HttpStatus.UNAUTHORIZED);
}

I have set resave: false in the session middleware to increase the cookie expiration time for each request. However, the problem is that even though the cookie expiration time increases, the cookie is not getting reset.

Can anyone please help me identify what might be causing this issue? I would appreciate any guidance or suggestions to resolve this problem.


Solution

  • You need to set the rolling option to true