Bird
Raised Fist0
NestJSframework~10 mins

File validation pipe in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - File validation pipe
File Upload Request
↓
Pipe Receives File
↓
Validate File Type?
No→Throw Error: Invalid Type
Yes↓
Validate File Size?
No→Throw Error: File Too Large
Yes↓
Pass Valid File to Controller
↓
Controller Processes File
The file validation pipe checks the uploaded file's type and size before allowing it to reach the controller.
Execution Sample
NestJS
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';

@Injectable()
export class FileValidationPipe implements PipeTransform {
  transform(file: Express.Multer.File) {
    if (!file) throw new BadRequestException('No file uploaded');
    if (!['image/png', 'image/jpeg'].includes(file.mimetype)) {
      throw new BadRequestException('Invalid file type');
    }
    if (file.size > 1024 * 1024) {
      throw new BadRequestException('File too large');
    }
    return file;
  }
}
This pipe checks if a file exists, then validates its type and size, throwing errors if invalid.
Execution Table
StepActionInput FileCheckResultNext Step
1Receive file{mimetype: 'image/png', size: 500000}File exists?YesValidate type
2Validate typeimage/pngIs type in ['image/png', 'image/jpeg']?YesValidate size
3Validate size500000 bytesIs size <= 1MB?YesReturn file
4ReturnValid fileN/AFile passed validationController receives file
5Receive filenullFile exists?NoThrow error: No file uploaded
6Receive file{mimetype: 'application/pdf', size: 500000}File exists?YesValidate type
7Validate typeapplication/pdfIs type in ['image/png', 'image/jpeg']?NoThrow error: Invalid file type
8Receive file{mimetype: 'image/jpeg', size: 2000000}File exists?YesValidate type
9Validate typeimage/jpegIs type in ['image/png', 'image/jpeg']?YesValidate size
10Validate size2000000 bytesIs size <= 1MB?NoThrow error: File too large
💡 Execution stops when file fails validation or passes all checks successfully.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
fileundefined{mimetype: 'image/png', size: 500000}{mimetype: 'image/png', size: 500000}{mimetype: 'image/png', size: 500000}Returned valid file
fileundefinednullnullnullError thrown: No file uploaded
fileundefined{mimetype: 'application/pdf', size: 500000}{mimetype: 'application/pdf', size: 500000}N/AError thrown: Invalid file type
fileundefined{mimetype: 'image/jpeg', size: 2000000}{mimetype: 'image/jpeg', size: 2000000}{mimetype: 'image/jpeg', size: 2000000}Error thrown: File too large
Key Moments - 3 Insights
Why does the pipe throw an error if the file is null?
Because the pipe first checks if a file exists (Step 1 in execution_table). If the file is null or undefined, it immediately throws a 'No file uploaded' error to prevent further processing.
What happens if the file type is not in the allowed list?
At Step 7 in execution_table, if the file mimetype is not 'image/png' or 'image/jpeg', the pipe throws an 'Invalid file type' error and stops execution.
How does the pipe handle files larger than 1MB?
At Step 10, the pipe checks the file size. If it exceeds 1MB (1024*1024 bytes), it throws a 'File too large' error, preventing the file from reaching the controller.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the result at Step 3 when the file size is 500000 bytes?
AFile size is valid, proceed to return file
BFile size is too large, throw error
CFile type is invalid, throw error
DNo file uploaded error
💡 Hint
Check Step 3 row in execution_table for file size validation result.
At which step does the pipe throw an error for an unsupported file type?
AStep 10
BStep 2
CStep 7
DStep 5
💡 Hint
Look for the step where file mimetype is checked against allowed types and error is thrown.
If the file is missing, what will the variable 'file' be at Step 1 and what happens next?
A'file' is valid, pipe continues validation
B'file' is null, pipe throws 'No file uploaded' error
C'file' is undefined, pipe returns file
D'file' is null, pipe accepts file
💡 Hint
Refer to variable_tracker and execution_table Step 5 for file null check.
Concept Snapshot
File Validation Pipe in NestJS:
- Implements PipeTransform interface
- Checks if file exists
- Validates file mimetype against allowed list
- Validates file size limit
- Throws BadRequestException on failure
- Passes valid file to controller
- Ensures safe file uploads
Full Transcript
This visual execution trace shows how a NestJS file validation pipe works step-by-step. When a file upload request arrives, the pipe first checks if a file is present. If not, it throws a 'No file uploaded' error. If a file exists, it checks the file type against allowed types like 'image/png' and 'image/jpeg'. If the type is invalid, it throws an error. Next, it checks the file size to ensure it does not exceed 1MB. If the file is too large, it throws an error. If all checks pass, the pipe returns the valid file to the controller for further processing. The variable tracker shows how the file variable changes or triggers errors at each step. Key moments clarify common confusions about missing files, invalid types, and size limits. The quiz questions help reinforce understanding by referencing specific steps and variable states in the execution table.

Practice

(1/5)
1. What is the main purpose of a FileValidationPipe in NestJS?
easy
A. To upload files to a cloud storage service
B. To convert files into JSON format automatically
C. To check uploaded files for type, size, and presence before processing
D. To compress files before saving them

Solution

  1. 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.
  2. Step 2: Apply this to file uploads

    A FileValidationPipe specifically checks uploaded files for correct type, size, and presence to prevent bad data.
  3. Final Answer:

    To check uploaded files for type, size, and presence before processing -> Option C
  4. Quick Check:

    File validation = check file properties [OK]
Hint: Validation pipes check data early to keep apps safe [OK]
Common Mistakes:
  • Thinking pipes upload or transform files
  • Confusing validation with file storage
  • Assuming pipes compress files automatically
2. Which of the following is the correct way to apply a file validation pipe to a file upload in a NestJS controller?
easy
A. @UsePipes(new FileValidationPipe()) uploadFile(@UploadedFile() file: Express.Multer.File) {}
B. @UseGuards(new FileValidationPipe()) uploadFile(@UploadedFile() file: Express.Multer.File) {}
C. @UseFilters(new FileValidationPipe()) uploadFile(@UploadedFile() file: Express.Multer.File) {}
D. @UseInterceptors(new FileValidationPipe()) uploadFile(@UploadedFile() file: Express.Multer.File) {}

Solution

  1. Step 1: Identify the correct decorator for validation pipes

    In NestJS, validation pipes are applied using the @UsePipes() decorator.
  2. Step 2: Match the usage with file upload

    The FileValidationPipe is a pipe, so it must be passed inside @UsePipes() to validate the uploaded file.
  3. Final Answer:

    @UsePipes(new FileValidationPipe()) uploadFile(@UploadedFile() file: Express.Multer.File) {} -> Option A
  4. Quick Check:

    Validation pipe = @UsePipes() [OK]
Hint: Use @UsePipes() for validation pipes, not guards or filters [OK]
Common Mistakes:
  • Using @UseGuards or @UseFilters instead of @UsePipes
  • Applying pipes without instantiating them
  • Confusing interceptors with pipes
3. Given this pipe code snippet, what will happen if a user uploads a file larger than 1MB?
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;
  }
}
medium
A. The pipe ignores the size and processes the file
B. The pipe accepts the file and returns it
C. The pipe throws a NotFoundException
D. The pipe throws a BadRequestException with message 'File too large'

Solution

  1. Step 1: Analyze the size check in the transform method

    The pipe checks if file.size is greater than 1,000,000 bytes (1MB).
  2. Step 2: Understand the exception thrown on size violation

    If the file is too large, it throws BadRequestException('File too large'), stopping the request.
  3. Final Answer:

    The pipe throws a BadRequestException with message 'File too large' -> Option D
  4. Quick Check:

    File size > 1MB = BadRequestException [OK]
Hint: Check exception messages in transform() for validation errors [OK]
Common Mistakes:
  • Assuming the pipe accepts large files
  • Confusing BadRequestException with NotFoundException
  • Ignoring the file presence check
4. Identify the error in this file validation pipe code:
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;
  }
}
medium
A. The mimetype check always throws because of incorrect logical operator
B. The file presence check is missing
C. The pipe does not return the file
D. The exception type is incorrect

Solution

  1. Step 1: Examine the mimetype condition

    The condition uses || (OR) between two checks: file.mimetype !== 'image/png' OR file.mimetype !== 'image/jpeg'.
  2. 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.
  3. Final Answer:

    The mimetype check always throws because of incorrect logical operator -> Option A
  4. Quick Check:

    Use AND (&&) to check mimetype correctly [OK]
Hint: Use && to check if mimetype is neither png nor jpeg [OK]
Common Mistakes:
  • Using || instead of && in mimetype checks
  • Forgetting to return the file after validation
  • Throwing wrong exception types
5. You want to create a file validation pipe that only accepts PDF files smaller than 2MB and throws a clear error if validation fails. Which of the following code snippets correctly implements this?
hard
A. 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; } }
B. 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; } }
C. export class PdfValidationPipe implements PipeTransform { transform(file: Express.Multer.File) { if (!file) throw new BadRequestException('File is required'); if (file.mimetype !== 'application/pdf' && file.size > 2_000_000) throw new BadRequestException('Invalid file'); return file; } }
D. export class PdfValidationPipe implements PipeTransform { transform(file: Express.Multer.File) { if (!file) throw new BadRequestException('File is required'); if (file.mimetype !== 'application/pdf' || file.size > 2_000_000) throw new BadRequestException('Invalid file'); return file; } }

Solution

  1. Step 1: Verify correct logic for presence and mimetype

    Check if (!file) throw, then if (file.mimetype !== 'application/pdf') throw 'Only PDFs allowed'. Uses !== to reject non-PDFs.
  2. 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.
  3. Step 3: Eliminate distractors

    B throws if PDF; C's && accepts non-PDF if small; D's > accepts exactly 2MB.
  4. 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 B
  5. Quick Check:

    !== mimetype, >= size, separate ifs [OK]
Hint: Check each condition separately with !== and clear exceptions [OK]
Common Mistakes:
  • Using === instead of !== for mimetype check
  • Combining conditions incorrectly with && or ||
  • Not throwing specific error messages
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard