Open In App

How To Fix "PayloadTooLargeError: request entity too large" in Nest.JS?

Last Updated : 17 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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

sdef
Folder Structure

Dependencies

"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