Discover how a simple pipe can save you from endless file validation headaches!
Why File validation pipe in NestJS? - Purpose & Use Cases
Imagine building a file upload feature where you manually check each file's size, type, and format in every controller method.
You write repetitive code to reject invalid files and handle errors everywhere.
Manually validating files is slow and error-prone.
You might forget checks, duplicate code, or handle errors inconsistently.
This leads to bugs, security risks, and poor user experience.
A file validation pipe centralizes all file checks in one place.
It automatically validates files before they reach your controller logic.
This keeps your code clean, consistent, and secure.
if (!file || file.size > MAX_SIZE || !allowedTypes.includes(file.mimetype)) { throw new BadRequestException('Invalid file'); }
@UsePipes(new FileValidationPipe({ maxSize: MAX_SIZE, allowedTypes }))You can easily enforce file rules everywhere with reusable, clean, and secure validation.
Uploading profile pictures where only images under 2MB are accepted, and invalid files are rejected automatically.
Manual file checks cause repeated, error-prone code.
File validation pipes centralize and automate file checks.
This improves security, consistency, and developer productivity.
Practice
FileValidationPipe in NestJS?Solution
Step 1: Understand the role of validation pipes in NestJS
Validation pipes are used to check and validate incoming data before it reaches the controller logic.Step 2: Apply this to file uploads
AFileValidationPipespecifically checks uploaded files for correct type, size, and presence to prevent bad data.Final Answer:
To check uploaded files for type, size, and presence before processing -> Option CQuick Check:
File validation = check file properties [OK]
- Thinking pipes upload or transform files
- Confusing validation with file storage
- Assuming pipes compress files automatically
Solution
Step 1: Identify the correct decorator for validation pipes
In NestJS, validation pipes are applied using the@UsePipes()decorator.Step 2: Match the usage with file upload
TheFileValidationPipeis a pipe, so it must be passed inside@UsePipes()to validate the uploaded file.Final Answer:
@UsePipes(new FileValidationPipe()) uploadFile(@UploadedFile() file: Express.Multer.File) {} -> Option AQuick Check:
Validation pipe = @UsePipes() [OK]
- Using @UseGuards or @UseFilters instead of @UsePipes
- Applying pipes without instantiating them
- Confusing interceptors with pipes
export class FileValidationPipe implements PipeTransform {
transform(file: Express.Multer.File) {
if (!file) throw new BadRequestException('File is required');
if (file.size > 1_000_000) throw new BadRequestException('File too large');
return file;
}
}Solution
Step 1: Analyze the size check in the transform method
The pipe checks iffile.sizeis greater than 1,000,000 bytes (1MB).Step 2: Understand the exception thrown on size violation
If the file is too large, it throwsBadRequestException('File too large'), stopping the request.Final Answer:
The pipe throws a BadRequestException with message 'File too large' -> Option DQuick Check:
File size > 1MB = BadRequestException [OK]
- Assuming the pipe accepts large files
- Confusing BadRequestException with NotFoundException
- Ignoring the file presence check
export class FileValidationPipe implements PipeTransform {
transform(file: Express.Multer.File) {
if (!file) throw new BadRequestException('File is required');
if (file.mimetype !== 'image/png' || file.mimetype !== 'image/jpeg') {
throw new BadRequestException('Invalid file type');
}
return file;
}
}Solution
Step 1: Examine the mimetype condition
The condition uses||(OR) between two checks:file.mimetype !== 'image/png'ORfile.mimetype !== 'image/jpeg'.Step 2: Understand why this always triggers
Because a file cannot be both 'image/png' and 'image/jpeg' at the same time, one of these will always be true, causing the exception every time.Final Answer:
The mimetype check always throws because of incorrect logical operator -> Option AQuick Check:
Use AND (&&) to check mimetype correctly [OK]
- Using || instead of && in mimetype checks
- Forgetting to return the file after validation
- Throwing wrong exception types
Solution
Step 1: Verify correct logic for presence and mimetype
Checkif (!file)throw, thenif (file.mimetype !== 'application/pdf')throw 'Only PDFs allowed'. Uses!==to reject non-PDFs.Step 2: Separate size check for smaller than 2MB
if (file.size >= 2_000_000)throw 'File too large'. Uses>=to reject 2MB or larger.Step 3: Eliminate distractors
B throws if PDF; C's&&accepts non-PDF if small; D's>accepts exactly 2MB.Final Answer:
export class PdfValidationPipe implements PipeTransform { transform(file: Express.Multer.File) { if (!file) throw new BadRequestException('File is required'); if (file.mimetype !== 'application/pdf') throw new BadRequestException('Only PDFs allowed'); if (file.size >= 2_000_000) throw new BadRequestException('File too large'); return file; } } -> Option BQuick Check:
!== mimetype, >= size, separate ifs [OK]
- Using === instead of !== for mimetype check
- Combining conditions incorrectly with && or ||
- Not throwing specific error messages
Ready to prove it?
Pass the test and this pattern moves unknown
