I was previously initializing my session stuff in my NestJS main.ts
file, like this
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import * as cookieParser from 'cookie-parser';
import * as session from 'express-session';
import * as sessionFileStore from 'session-file-store';
import { AppModule } from './app.module';
async function bootstrap(): Promise<void> {
const app = await NestFactory.create<NestExpressApplication>(AppModule});
const sessionTimeToLiveInSeconds = 60 * 60 * 12; //43200 seconds = 12 days
const cookieMaxAgeInMilliseconds = 1000 * 60 * 60 * 24 * 7; //604800000 ms = 1 week
const FileStore = sessionFileStore(session);
const appFileStore = new FileStore({
path: './sessions/',
ttl: sessionTimeToLiveInSeconds,
});
app.use(
session({
secret: process.env.secret,
resave: true,
store: appFileStore,
saveUninitialized: true,
cookie: {
secure: process.env.environment !== 'dev',
httpOnly: false,
sameSite: false,
maxAge: cookieMaxAgeInMilliseconds,
},
}),
);
app.use(cookieParser(process.env.secret)); //Allow session cookies
//other stuff here...
});
And then I discovered the nestjs-session
project, so I’ve installed it and moved everything over to my app.module.ts
import { Module } from '@nestjs/common';
import * as session from 'express-session';
import { NestSessionOptions, SessionModule } from 'nestjs-session';
import * as sessionFileStore from 'session-file-store';
@Module({
imports: [
SessionModule.forRootAsync({
useFactory: (): NestSessionOptions => {
const sessionTimeToLiveInSeconds = 60 * 60 * 12; //43200 seconds = 12 days
const cookieMaxAgeInMilliseconds = 1000 * 60 * 60 * 24 * 7; //604800000 ms = 1 week
const FileStore = sessionFileStore(session);
const appFileStore = new FileStore({
path: './sessions/',
ttl: sessionTimeToLiveInSeconds,
});
return {
session: {
secret: process.env.secret,
resave: true,
store: appFileStore,
saveUninitialized: true,
cookie: {
secure: process.env.environment !== 'dev',
httpOnly: false,
sameSite: false,
maxAge: cookieMaxAgeInMilliseconds,
},
},
};
},
}),
//other modules go here
],
controllers: [AppController],
})
export class AppModule {}
but when I try and do something that would access sessions I get:
ERROR [ExceptionsHandler] Login sessions require session support. Did you forget to use `express-session` middleware?
nestjs-session
project is supposed to allow me to set up session in a module without having to manually set it up as an express interceptor. But this error message seems to be saying that I MUST set it up in main.ts
.
I feel like either I am missing something obvious here or that the docs are missing some key information needed about how to set this up. What am I doing wrong?