How to cancel an incoming POST request in NodeJS sending a 4XX but without receiving the entire data?

A client can upload files to my NodeJS server. I want to make sure the client does not abuse the server and upload files that are too large. Therefore I want to cancel the request as soon as I detect a problem, but also return a meaningful status code and response to the client. Assume that the user uploads a file that is 100 MB large, but my server has a maximum file size of 10 MB.

If I do

req.socket.destroy()

the client will get a SocketException if in Java, or a canceled request in the browser.

Is there a better way to send an elegant response and in the same time avoid receiving the entire 100 MB file?

From 413 Request Entity Too Large

The server is refusing to process a request because the request entity is larger than the server is willing or able to process. The server MAY close the connection to prevent the client from continuing the request.

So according to the protocol you should first send a 413 response and then close the connection.

Try

res.writeHead(413, {'Content-Type': 'text/plain'});
res.end('10mb max.');