Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslnode 18–226 runs
build_error
glibcnode 18–226 runs
build_error
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
NestjsFormDataModule
✓ import { NestjsFormDataModule } from 'nestjs-form-data'
✗ const { NestjsFormDataModule } = require('nestjs-form-data')
Main module to be imported into your NestJS application (e.g., AppModule) to enable form data processing. Use `NestjsFormDataModule.config()` for global options.
FormDataRequest
✓ import { FormDataRequest } from 'nestjs-form-data'
✗ import FormDataRequest from 'nestjs-form-data'
Decorator applied to controller methods (`@Post()`, `@Patch()`, etc.) to activate form data parsing for that specific route. It's a named import.
MemoryStoredFile
✓ import { MemoryStoredFile } from 'nestjs-form-data'
Represents an uploaded file stored in memory. It's a concrete implementation of `StoredFile` and is commonly used in DTOs for smaller files.
IsFile, MaxFileSize, HasMimeType
✓ import { IsFile, MaxFileSize, HasMimeType } from 'nestjs-form-data'
✗ import { IsFile } from 'class-validator'
These are custom validation decorators provided by `nestjs-form-data` specifically for file properties within DTOs. `class-validator` itself needs to be installed as a peer dependency.
This quickstart demonstrates how to set up `nestjs-form-data` to handle a single file upload along with a text field. It defines a DTO with file-specific validation decorators, applies the `@FormDataRequest()` decorator to a controller method, and configures a global `ValidationPipe` for DTO transformation.
import { NestFactory } from '@nestjs/core';
import { ValidationPipe, Module, Controller, Post, Body } from '@nestjs/common';
import { NestjsFormDataModule, FormDataRequest, MemoryStoredFile, IsFile, MaxFileSize, HasMimeType } from 'nestjs-form-data';
// 1. Define your DTO for file upload and form fields
class UploadAvatarDto {
@IsFile()
@MaxFileSize(1e6, { message: 'Avatar file size must not exceed 1MB' })
@HasMimeType(['image/jpeg', 'image/png'], { message: 'Avatar must be a JPEG or PNG image' })
avatar: MemoryStoredFile;
@Body('userId')
userId: string;
}
// 2. Create your controller
@Controller('users')
export class UsersController {
@Post('avatar')
@FormDataRequest() // Apply the decorator to enable form data parsing
uploadAvatar(@Body() dto: UploadAvatarDto) {
// dto.avatar is now a MemoryStoredFile instance
console.log(`User ${dto.userId} uploaded avatar:`);
console.log(`Original Name: ${dto.avatar.originalName}`);
console.log(`Size: ${dto.avatar.size} bytes`);
console.log(`MIME Type: ${dto.avatar.mimeType}`);
console.log(`Buffer length: ${dto.avatar.buffer.length}`);
// In a real application, you would save dto.avatar.buffer to storage (e.g., S3, local disk)
return { message: `Avatar for user ${dto.userId} uploaded successfully!` };
}
}
// 3. Register the module and global validation pipe
@Module({
imports: [
NestjsFormDataModule.config({
is// Enable file system storage by default, or keep MemoryStoredFile as default
// storage: FileSystemStoredFile,
}),
],
controllers: [UsersController],
})
export class AppModule {}
// 4. Bootstrap your NestJS application
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(
new ValidationPipe({
transform: true, // Crucial for DTO transformation and file object hydration
whitelist: true, // Recommended for security
forbidNonWhitelisted: true, // Recommended for security
}),
);
await app.listen(3000);
console.log('Application is running on: http://localhost:3000');
}
bootstrap();
Debug
Known issues
breakingThe configuration option `autoDeleteFile` was deprecated in favor of more granular control. It has been replaced by two separate fields: `cleanupAfterSuccessHandle` and `cleanupAfterFailedHandle`.fixUpdate your `NestjsFormDataModule.config()` to use `cleanupAfterSuccessHandle: boolean` and `cleanupAfterFailedHandle: boolean` instead of `autoDeleteFile`.
affects: >=1.9.7
breakingA prototype pollution vulnerability via multipart field names (`__proto__[key]`) was fixed. The internal form-data result object is now created with `Object.create(null)` to prevent inherited properties from being modified.fixUpgrade to `v11.0.0` or later to mitigate the prototype pollution vulnerability. This change might subtly affect applications that previously relied on inherited properties on the parsed form data object (though this is highly unlikely and discouraged).
affects: <11.0.0
gotchaThe `HasMimeType` validator's `strictSource` parameter was silently ignored in versions prior to `v11.0.0`. It now correctly enforces the source for MIME type detection, which might alter validation behavior for existing configurations.fixReview your usage of `@HasMimeType` decorators with the `strictSource` option after upgrading to `v11.0.0+` to ensure desired validation behavior. Adjust the `strictSource` setting if necessary.
affects: <11.0.0
breakingA race condition where file cleanup (using `deleteFiles()`) was not consistently awaited before sending the response was fixed. Cleanup is now properly awaited by default. A new `awaitCleanup` configuration option (default `true`) was added to allow for fire-and-forget cleanup for faster response times.fixUpgrade to `v11.0.1`. If you need to revert to a fire-and-forget cleanup for faster responses, configure `awaitCleanup: false` in `NestjsFormDataModule.config()`.
affects: <11.0.1
gotchaA global `ValidationPipe` with `transform: true` is crucial for `nestjs-form-data` to correctly transform incoming request bodies into DTO instances and hydrate `StoredFile` objects, especially for file arrays. Without it, file properties might be `undefined` or plain objects.fixEnsure your `main.ts` includes `app.useGlobalPipes(new ValidationPipe({ transform: true }))`. affects: *
gotchaThis package explicitly requires Node.js version 20 or higher. Using older versions may lead to unexpected behavior or installation issues.fixUpgrade your Node.js environment to version 20 or newer.
affects: <20.0.0 (Node.js)
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading 'originalName')
The DTO property for the file (e.g., `dto.avatar`) is `undefined` or not a `StoredFile` instance, often due to missing `@FormDataRequest()` decorator or incorrect `ValidationPipe` configuration.
fixVerify that `@FormDataRequest()` is applied to your controller method and that `app.useGlobalPipes(new ValidationPipe({ transform: true }))` is configured in `main.ts`. HttpException: Request must have a Content-Type of multipart/form-data
The client making the request is not sending the `Content-Type` header as `multipart/form-data`, which is necessary for file uploads.
fixEnsure your client-side code (e.g., HTML form, Axios, Fetch API) correctly sets `Content-Type: multipart/form-data` and sends the data in the appropriate format. For HTML forms, `enctype="multipart/form-data"` is needed.
BadRequestException: Invalid mime type
The MIME type of the uploaded file does not match any of the allowed types specified in the `@HasMimeType()` decorator on your DTO property.
fixCheck the `mimeTypes` array passed to `@HasMimeType()` in your DTO to ensure it includes the expected MIME types for the files being uploaded. Also, review the `strictSource` option if on `v11.0.0+`.
BadRequestException: File size exceeds the allowed limit
The size of the uploaded file is larger than the maximum allowed size configured in the `@MaxFileSize()` decorator.
fixIncrease the `maxSize` value (in bytes) provided to the `@MaxFileSize()` decorator in your DTO or adjust the `maxFileSize` global configuration in `NestjsFormDataModule.config()`.
Audit
Dependencies
@nestjs/commonrequiredRequired for NestJS core functionalities like decorators, pipes, and modules.
@nestjs/corerequiredEssential for bootstrapping NestJS applications and core runtime.
class-transformerrequiredUsed for transforming plain objects to DTO instances, crucial for hydrating file objects.
class-validatorrequiredEnables declarative validation of DTO properties, including custom file validators.
reflect-metadatarequiredRequired by NestJS and `class-transformer` for decorator-based metadata reflection.
rxjsrequiredA peer dependency of NestJS itself, used for reactive programming patterns.