Search code examples
nestjsnestjs-config

What is the difference depending on where the global validation pipe is set in Nest.js?


There are two different ways to apply validation pipe globally. I can't figure out the difference between those.

method 1

// app.module.ts

import { APP_PIPE } from '@nestjs/core';

@Module({
  providers: [    
    {
      provide: APP_PIPE, // <-- here
      useValue: new ValidationPipe({}),
    },
  ]
})
export class AppModule implements NestModule {
  // ...
}

method 2

https://docs.nestjs.com/techniques/validation#auto-validation

// main.ts

async function bootstrap() {
  const app = await NestFactory.create(AppModule); 
  app.useGlobalPipes(new ValidationPipe({})); // <-- here
  await app.listen(3000);
}
bootstrap();

Solution

  • When we are applying a global validation pipe in main.ts we bind the validation pipe throughout the application. But it does miss out on the modules registered from outside the context of the application. On the other hand, when we apply a validation pipe in the module scope the pipe binds on only the routes for that module. This becomes pretty useful when you want to bind specific pipes to a module.