1
votes

The NestJS class or functional middleware doesn't run when connected from a Module. It is also not working for a single path, controller or for every path. Connecting functional middleware from main.ts works fine.

//main.ts
import { ValidationPipe } from '@nestjs/common'
import { NestFactory } from '@nestjs/core'
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify'
import { AppModule } from './app.module'

declare const module: any

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

  app.useGlobalPipes(new ValidationPipe())

  await app.listen(2100)

  if (module.hot) {
    module.hot.accept()
    module.hot.dispose(() => app.close())
  }
}
bootstrap()
//app.module.ts
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'
import { AuthMiddleware } from './middleware/auth.middleware'
import { UserModule } from './user/user.module'

@Module({
  imports: [UserModule],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(AuthMiddleware)
      .forRoutes('(.*)')
  }
}
//auth.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common'
import { FastifyRequest, FastifyReply } from 'fastify'

@Injectable()
export class AuthMiddleware implements NestMiddleware {
  use(req: FastifyRequest, res: FastifyReply, next: () => void) {
    console.log('test auth middleware')
    next()
  }
}

Expected output: test auth middleware
Actual: nothing

1

1 Answers

6
votes

The problem was installing the "fastify" package along with "@nestjs/platform-fastify". In addition, if you remove the "fastify" package, then the dependencies used in the "@nestjs/platform-fastify" package are also removed, so it won't work correctly. If you've installed both packages, uninstall "fastify" and reinstall "@nestjs/platform-fastify".