How To Fix "PayloadTooLargeError: request entity too large" in Nest.JS?
Last Updated :
17 Sep, 2024
The PayloadTooLargeError occurs when a request payload exceeds the maximum size limit set by the server. In NestJS, which uses Express by default, this limit is typically set to around 100KB. When a client sends a payload larger than this limit, the server cannot process it and throws the PayloadTooLargeError. This error helps prevent abuse and manage server resources by limiting the size of incoming data.
Overview of the PayloadTooLargeError
The "PayloadTooLargeError" in NestJS is an HTTP error that occurs when the size of the incoming request body exceeds the configured limit of the server or middleware handling the request. This error is represented by the HTTP status code 413 (Payload Too Large), signalling that the server is refusing to process the request due to its size.
Common Scenarios That Trigger This Error in NestJS
- Large JSON Payloads: Sending large JSON data that exceeds the default size limit set by the body parser.
- File Uploads: Uploading files that exceed the server or middleware's configured file size limits.
- Form Submissions: Submitting forms with extensive data, especially with large text fields or multiple file attachments.
How NestJS Handles Request Sizes by Default?
By default, NestJS uses body parsing middleware to handle incoming requests, specifically JSON and URL-encoded data. The default body parser settings have size limits to avoid potential issues with large payloads, such as denial-of-service (DoS) attacks or high memory consumption. These limits are typically around 100 KB for JSON payloads and URL-encoded data.
1. Using Body Parser Configuration
Configuring JSON Body Parser
In main.ts, you can adjust the size limit for JSON payloads as follows:
app.use(json({ limit: '10mb' }));
2. Configuring URL-Encoded Body Parser
Similarly, adjust the URL-encoded body parser limit:
app.use(urlencoded({ extended: true, limit: '10mb' }));
3. Using Middleware to Control Request Size
You can use custom middleware in NestJS to control request size dynamically.
Example Middleware for Adjusting Size Limits
import { Injectable, NestMiddleware } from '@nestjs/common';
@Injectable()
export class SizeLimitMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) {
if (req.headers['content-length'] > 10485760) {
return res.status(413).send('Payload too large');
}
next();
}
}
4. Handling File Uploads
In file upload scenarios, you need to configure Multer for setting appropriate file size limits.
When using Multer for file uploads, specify the size limits like this:
import { MulterModule } from '@nestjs/platform-express';
MulterModule.register({
limits: { fileSize: 10 * 1024 * 1024 }, // 10MB limit
});
5. Adjusting Limits in File Upload Routes
When defining your routes, ensure the size limit is set appropriately:
@Post('upload')
@UseInterceptors(FileInterceptor('file', {
limits: { fileSize: 10 * 1024 * 1024 }, // 10MB limit
}))
uploadFile(@UploadedFile() file: Express.Multer.File) {
console.log(file);
}
Steps To Fix the Error
1. Create a Basic NestJS Application
First, if you don't have a NestJS application set up, create one using the Nest CLI:
nest new nestjs-env
cd nestjs-env
Folder Structure
Folder StructureDependencies
"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/config": "^3.2.3",
"@nestjs/core": "^10.0.0",
"@nestjs/platform-express": "^10.0.0",
"@types/multer": "^1.4.12",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1"
}
2. Set Up the Main Application File
- bodyParser.json({ limit: '10mb' }): This increases the limit for JSON payloads to 10MB. You can adjust this size based on your needs.
- bodyParser.urlencoded({ limit: '10mb', extended: true }): This increases the limit for URL-encoded payloads (typically used in form submissions) to 10MB.
Example:
JavaScript
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as bodyParser from 'body-parser';
import { SizeLimitMiddleware } from './size-limit.middleware';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Method 1: Configure Body Parser
app.use(bodyParser.json({ limit: '10mb' }));
app.use(bodyParser.urlencoded({ limit: '10mb', extended: true }));
// Method 2: Apply Custom Middleware for Request Size
app.use(new SizeLimitMiddleware().use);
await app.listen(3000);
}
bootstrap();
JavaScript
// app.controller.ts
import {
Controller,
Post,
UploadedFile,
UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Express } from 'express';
@Controller('upload')
export class AppController {
@Post()
@UseInterceptors(FileInterceptor('file'))
uploadFile(@UploadedFile() file: Express.Multer.File) {
console.log('File uploaded:', file);
return {
message: 'File uploaded successfully',
fileName: file.originalname,
};
}
}
JavaScript
// app.module.ts
import { Module } from '@nestjs/common';
import { MulterModule } from '@nestjs/platform-express';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [
MulterModule.register({
limits: {
fileSize: 10 * 1024 * 1024,
},
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule { }
JavaScript
// size-limit.middleware.ts
import {
Injectable,
NestMiddleware,
BadRequestException,
} from '@nestjs/common';
@Injectable()
export class SizeLimitMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) {
const contentLength = req.headers['content-length'];
const MAX_LIMIT = 10 * 1024 * 1024;
if (contentLength && Number(contentLength) > MAX_LIMIT) {
return res.status(413).send('Payload too large');
}
next();
}
}
3. Run the application:
npm start
Output:
Similar Reads
How to fix a 413: request entity too large error ? In this article, we will learn about an Error request entity too large which typically occurs when the size of the data, being sent to a server, exceeds the maximum limit allowed by the server or the web application in web development when handling file uploads, form submissions, or any other data s
4 min read
How To Send POST Request To External API In NextJS? Sending POST requests to external APIs in Next.js enables interaction with third-party services or your backend. This allows for data submission, form handling, and integration, enhancing your application's functionality.Prerequisites:NextJSJavaScriptReactJSBelow are the approaches mentioned to send
4 min read
Postman - How to Sent .json File as POST Data Payload within Pre-request Script? Postman is quite a popular tool that is primarily used for API testing. There are various features in this including sending different kinds of requests to the web servers and getting the responses in real time. In this article, we will be focusing on how to use the Postman to send .json files as PO
3 min read
How to Fix HTTP 429 Error Too Many Requests Have you encountered the HTTP 429 error while browsing or working on your website? Itâs a common issue that can disrupt your online activities, and understanding it is crucial for efficient troubleshooting. The HTTP 429 Too Many Requests error occurs when youâve exceeded the number of allowed reques
9 min read
How to read Array of Nested JSON Response in Postman ? We know that the postman is the one who delivers the letters sent by your friends, colleagues, or relatives and acts as a bridge of communication. Here Postman refers to the development of API that acts as a bridge or communication between different programs. In other words, it is an API client, mad
3 min read
How To Perform Unit Test in NestJS? NestJS is a Node.js framework for building efficient, reliable and scalable server-side applications. It is built using TypeScript and It offers support for unit testing through the Jest testing framework. In this article, we will learn about performing unit testing in a NestJs.Table of ContentWhat
5 min read