How to stop large file upload on NextJs

I’m writing an app in NextJs that has a form that uploads an image.
Image file size should be limited, so of course there is code that in client side limits file size, but as you know those limitations could be easily skipped. So I want to limit file size upload also on server side. I use a server action to process form data, the problem is that I don’t get file info till image is effectively transfered to server. What I want is to abort file send immediately, for that I’ve createad a middleware that intercept the post inspecting content-length and returning a propper error if content length excess some certain value. Such header validation occurs immediately, no file upload occurred, but the response isn’t sent to client till file is uploaded.

middleware.js

import { NextResponse } from "next/server";

const MAX_CONTENT_LENGTH = 10000;

export async function middleware(request) {
    if (request.method === "POST") {
        if (request.url.endsWith("/meals/share")) {
            const contentLength = +request.headers.get("Content-Length");
            if (contentLength > MAX_CONTENT_LENGTH) {
                return NextResponse.json(
                    {
                         message: `Images cannot be larger than ${MAX_CONTENT_LENGTH}`,
                     },
                     { status: 400 }
                 );
            }
        }
    }
    return NextResponse.next();
}

This code works, but has the flaw I’ve mentioned, the file gets uploaded anyway, I’ve verified this testing uploads with very large files (10gb) and response delay is proportional to file size.
The question is how do I abort file upload so the response returns immediately?

in express, multer library is used to handle the size. next.js has bodysizelimit

By default, the maximum size of the request body sent to a Server
Action is 1MB, to prevent the consumption of excessive server
resources in parsing large amounts of data, as well as potential DDoS
attacks.

However, you can configure this limit using the
serverActions.bodySizeLimit option. It can take the number of bytes or
any string format supported by bytes, for example 1000, ‘500kb’ or
‘3mb’.

// next.config.js
module.exports = {
  experimental: {
    serverActions: {
      bodySizeLimit: '2mb',
    },
  },
}

Leave a Comment