Unknown Fields
Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 16 of 24.
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
EasyA client can send fields your DTO never mentions, like "owner": "admin", and right now they reach your code untouched. Make the API refuse them, so a client with a typo or a sneaky extra field finds out.
- In
src/main.ts, find theValidationPipethatbootstrapalready registers. Pass it two options:whitelist: true, which removes every field without a validation decorator, andforbidNonWhitelisted: true, which refuses such a body with 400 instead of removing the field. The second option only works together with the first. - Change nothing else. Bodies with only
titleanddonekeep working, and a bad title is still refused.
Try it: POST { "title": "Book flights", "owner": "admin" } to /tasks. You get 400:
{ "message": ["property owner should not exist"], "error": "Bad Request", "statusCode": 400 }Then POST { "title": "Book flights" }: 201 and the new task. { "title": 7 } still gets 400.
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();
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in TypeScript and NestJS
Practice on your own: Express playground