Menu
CoddyTech

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 icon

Challenge

Easy

A 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.

  1. In src/main.ts, find the ValidationPipe that bootstrap already registers. Pass it two options: whitelist: true, which removes every field without a validation decorator, and forbidNonWhitelisted: true, which refuses such a body with 400 instead of removing the field. The second option only works together with the first.
  2. Change nothing else. Bodies with only title and done keep 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();
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

Practice on your own: Express playground