~/javascript/next-js-solving-request-entity-too-large-issue-413.md

Request Entity Too Large(413) - Uploading File with Formdata with Axios and Custom header

2 min readJanuary 15, 2022by Gorav Singal#javascript#axios#nextjs
// TL;DR

The 413 Request Entity Too Large error when uploading files via Axios with form-data is caused by incorrect Content-Length; let Axios compute headers automatically instead of manually setting them.

Request Entity Too Large(413) - Uploading File with Formdata with Axios and Custom header

Introduction

I was trying to upload images to my backend using rest APIs. I was using form-data library with axios, so that I can pass authorization header as well.

I was getting error: Request Entity Too Large, with http Status of 413.

Earlier Code was:

const FormData = require("form-data");

const filepath = 'my-filepath';
let fileToUpload = new FormData();
fileToUpload.append("files", fs.createReadStream(filepath));

await axios.post(
    `${this._props.host}/upload`,
    fileToUpload,
    {
        headers: {
            Authorization: `Bearer ${this._jwt}`
        },
    }
);

Error:

Request failed with status code 413

Solution

You need to pass a header Content-Type with value of multipart/form-data; and a unique boundary. When using form-data library. It also gives you a method: getHeaders().

The code becomes:

const FormData = require("form-data");

const filepath = 'my-filepath';
let fileToUpload = new FormData();
fileToUpload.append("files", fs.createReadStream(filepath));

await axios.post(
    `${this._props.host}/upload`,
    fileToUpload,
    {
        headers: {
            ...fileToUpload.getHeaders(),
            Authorization: `Bearer ${this._jwt}`
        },
    }
);

If you print fileToUpload.getHeaders(), you will get

'content-type': 'multipart/form-data; boundary=--------------------------151840689896304164188529'

And, it works.

What is Unique Boundary

In simple terms, you know that the server knows that multiple parameters are separated by an ampersand (&) character. And, if user need to pass the ampersand (&) character in the request parameters, then it have to be encoded.

But, how the server will know when to read the file data and when to stop (start and end) in the case of multipart/form-data.

It has to be similar to ampersand philosophy or contract.

This unique boundary is used for that purpose. It is to tell the server how to split the data it receives in multipart/form-data. So, what is unique about it. This value has to be unique in the request. i.e. It should not come within the content of the request or the payload.

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Authenticating Strapi backend with Next.js and next-auth using credentials and jwt

Authenticating Strapi backend with Next.js and next-auth using credentials and jwt

Introduction Strapi is a backend system provides basic crud operations with…

Nextjs - Fixing Loading External Images and Issue of Url Paramater Not Allowed

Nextjs - Fixing Loading External Images and Issue of Url Paramater Not Allowed

Introduction In this post, we will see How to load external images to your next…

Nextjs - How to Build Next.js Application on Docker and Pass API Url

Nextjs - How to Build Next.js Application on Docker and Pass API Url

Introduction In this post we will see: How to prepare a docker image for your…

Nextjs - How to Redirect to Another Page and Pass State

Nextjs - How to Redirect to Another Page and Pass State

Introduction We have a page, for example a . And, upon submission we would want…

How to use Draft.js WYSWYG with Next.js and Strapi Backend, Edit/Update Saved Article

How to use Draft.js WYSWYG with Next.js and Strapi Backend, Edit/Update Saved Article

Introduction This post is in contuation of our previous post: How to use Draft…

Create Articles with Image Upload Using Draft.js, Next.js, and Strapi

Create Articles with Image Upload Using Draft.js, Next.js, and Strapi

Introduction In this post, we will use in Next.js with strapi. And, we will…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…