I have a Nestjs
application running with Fastify
. My goal is to implement the fastifySession
middleware using the MiddlewareConsumer
in Nestjs. Typically, the configuration looks like this:
configure(consumer: MiddlewareConsumer) {
consumer
.apply(
fastifySession,
)
.forRoutes({
path: '*',
method: RequestMethod.ALL,
});
}
}
The issue here is that the fastifySession
middleware requires an options
object. In a regular Fastify app, it would be set up using the register
method as follows:
app.register(fastifySession, {
secret: '',
cookie: {
secure: false,
domain: 'localhost',
},
store: new SessionStore(new SessionService()),
});
Instead of using the register
method directly in main.ts
, I want to leverage the Nestjs dependency injection by applying the middleware in the AppModule. Is there a way to achieve this?
UPDATE
I had the idea to create a custom Nestjs middleware to handle the registration of required Fastify plugins.
This is the middleware I developed:
@Injectable()
class FastifySession implements NestMiddleware {
private options;
private fastifyPassport;
constructor(
private adapterHost: HttpAdapterHost,
private sessionStore: SessionStore,
private userService: UserService,
) {
this.fastifyPassport = new Authenticator();
this.options = {
cookie: {
secure: false,
maxAge: 50000,
path: '/',
httpOnly: true,
sameSite: false,
domain: 'localhost',
},
store: this.sessionStore,
};
}
use(req: any, res: any, next: (error?: any) => void) {
const httpAdapter = this.adapterHost.httpAdapter;
const instance = httpAdapter.getInstance();
instance.register(fastifyCookie);
instance.register(fastifySession, this.options);
instance.register(this.fastifyPassport.initialize());
instance.register(this.fastifyPassport.secureSession());
this.fastifyPassport.registerUserSerializer(async (user: User, request) => {
console.log(user.id);
return user.id;
});
this.fastifyPassport.registerUserDeserializer(async (id, request) => {
const user = await this.userService.getUser(+id);
console.log('user ', user);
return user;
});
next();
}
}
I added the created middleware to my AppModule
export class AppModule implements NestModule {
constructor() {
}
configure(consumer: MiddlewareConsumer) {
consumer
.apply(FastifySession)
.forRoutes({
path: '*',
method: RequestMethod.ALL,
});
}
}
However, I encountered this error
ERROR [ExceptionsHandler] Root plugin has already booted
AvvioError: Root plugin has already booted
During my investigation, I came across this GitHub Issue
https://github.com/nestjs/nest/issues/1462
As per the insights in the GitHub issue, it seems registering Fastify plugins outside main.ts may not be feasible.
I would greatly appreciate any assistance or guidance in resolving this challenge!