Menu
CoddyTech

Unknown Fields

Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 12 of 17.

A client can send fields your DTO never mentions, like { "title": "x", "admin": true }, and they reach your code untouched. ValidationPipe has two options for them.

app.useGlobalPipes(
    new ValidationPipe({ whitelist: true }),
);

whitelist: true removes every field that has no validation decorator before your method sees the body. Add forbidNonWhitelisted: true and the pipe refuses such a body instead, with 400 and "property admin should not exist". forbidNonWhitelisted only works together with whitelist; on its own it does nothing.

Removing quietly suits a form that sends extra inputs. Refusing tells an API client about its typo, like titel.

challenge icon

Challenge

Easy
  • POST /tasks with a field CreateTaskDto does not declare answers 400 naming that field.
  • Valid bodies still answer 201.
  • Send POST /tasks with { "title": "Book flights", "owner": "admin" }, then with { "title": "Book flights" }.

Try it yourself

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

async function bootstrap() {
    const app = await NestFactory.create(AppModule);
    app.useGlobalPipes(new ValidationPipe());
    await app.listen(3000);
}
bootstrap();
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in TypeScript and NestJS