Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValidationPipe dont work when use app.useGlobalPipes

Hello. I wanna to use ValidationPipe globaly with useGlobalPipes. I use :

import 'dotenv/config';
import {NestFactory} from '@nestjs/core';
import {ValidationPipe} from '@nestjs/common';
import {AppModule} from './app.module';


async function bootstrap() {
    const app = await NestFactory.create(AppModule);
    app.useGlobalPipes(new ValidationPipe({
        transform: true,
        whitelist: true,
    }));
    await app.listen(3000);
}

bootstrap();

But this dont work. Work only when I add VAlidationPipe in my controler :

@Post('register')
@UsePipes(new ValidationPipe({ transform: true, whitelist: true}))
async register(@Body() userDTO: RegisterDTO) {
    const user = await this.userService.create(userDTO);
    const payload: Payload = {
        userName: user.userName,
        seller: user.seller,
    };

    const token = await this.authService.signPayload(payload);
    return {user, token};
}
like image 464
Anton Skybun Avatar asked Oct 31 '25 16:10

Anton Skybun


1 Answers

I came across the same issue, I found the solution was on https://docs.nestjs.com/pipes#global-scoped-pipes:

Global pipes are used across the whole application, for every controller and every route handler.

Note that in terms of dependency injection, global pipes registered from outside of any module (with useGlobalPipes() as in the example above) cannot inject dependencies since the binding has been done outside the context of any module. In order to solve this issue, you can set up a global pipe directly from any module using the following construction:

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

   @Module({
     providers: [
       {
         provide: APP_PIPE,
         useClass: ValidationPipe,
       },
     ],
   })
   export class AppModule {}

Having this in your AppModule makes the global validation pipe work.

like image 52
Rufus Avatar answered Nov 03 '25 07:11

Rufus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!