0
0
NestJSframework~30 mins

File validation pipe in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
File Validation Pipe in NestJS
📖 Scenario: You are building a NestJS backend that accepts file uploads. To keep your app safe and clean, you want to check that uploaded files meet certain rules before processing them.Imagine you run a photo sharing app. You want to accept only image files and limit their size to 1MB.
🎯 Goal: Create a custom file validation pipe in NestJS that checks if the uploaded file is an image and is smaller than 1MB.This pipe will help your app reject bad files early and keep your backend safe.
📋 What You'll Learn
Create a file validation pipe class named FileValidationPipe
Add a configuration variable maxFileSize set to 1_000_000 (1MB)
Implement the transform method to check file mimetype and size
Throw a BadRequestException if file is not an image or too large
💡 Why This Matters
🌍 Real World
File validation pipes help backend apps securely accept user uploads by checking file types and sizes before processing.
💼 Career
Backend developers often write custom pipes in NestJS to validate and transform incoming data, improving app security and reliability.
Progress0 / 4 steps
1
Create the FileValidationPipe class
Create a class called FileValidationPipe that implements PipeTransform from @nestjs/common. Import PipeTransform and BadRequestException from @nestjs/common.
NestJS
Need a hint?

Start by importing PipeTransform and BadRequestException. Then create a class named FileValidationPipe that implements PipeTransform. Add a transform method that returns the input value for now.

2
Add maxFileSize configuration
Inside the FileValidationPipe class, add a readonly property called maxFileSize and set it to 1_000_000 (1MB).
NestJS
Need a hint?

Add a property maxFileSize inside the class and set it to 1_000_000. Use readonly to prevent changes.

3
Implement file type and size checks in transform
In the transform method, check if value has a mimetype starting with 'image/' and a size less than or equal to this.maxFileSize. If either check fails, throw a BadRequestException with the message 'Invalid file type or file too large'. Otherwise, return value.
NestJS
Need a hint?

Use an if statement to check if value is missing, or if value.mimetype does not start with 'image/', or if value.size is greater than this.maxFileSize. Throw BadRequestException if any check fails.

4
Export and finalize the FileValidationPipe
Make sure the FileValidationPipe class is exported using export keyword so it can be used in other parts of the NestJS app.
NestJS
Need a hint?

Check that the class declaration starts with export so it can be imported elsewhere.