Reputation: 67
Why I want to pass errors from nginx to node.js
I want to limit the file size in a request when using nginx as a proxy server for Node.js and using multer for file upload. If I use limits
using multer's options, multer wastes a lot of bandwidth in trying to upload the file and later checks if it exceeds the limit but I can use my own error handling through node.js. When using client_max_body_size
in nginx, the request gets rejected altogether (more on that below).
The exact file size in the request is not the concern so client_max_body_size 100M;
works well. 100M is just a dummy value and won't be used for every route. Here is my nginx config
upstream my_nodejs_upstream {
server 127.0.0.1:5000;
keepalive 64;
}
server {
listen 80;
client_max_body_size 100M;
location / {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_http_version 1.1;
proxy_pass http://my_nodejs_upstream/;
proxy_redirect off;
proxy_read_timeout 240s;
}
}
Now, if a request body exceeds the limit (100M), I get the error: 413: Request Entity Too Large
. The error is returned as a static html page.
I'd like to know if an error for this status code (413) can be passed on to node.js and an error be sent from node.js instead. If not, what practice is generally used to handle such nginx errors in a consistent way while also keeping it maintainable?
Upvotes: 1
Views: 392
Reputation: 432
Needing to pass an error from NGINX to the API server would not be a good practice. Rather, in your front-end (e.g. web or mobile app) you could check for this 413 error and display it however you wish.
More generally, NGINX also supports custom error pages that you could read more about here: https://www.digitalocean.com/community/tutorials/how-to-configure-nginx-to-use-custom-error-pages-on-ubuntu-14-04.
Another option here is for you to create your own API endpoint that simply checks whether the POST request will be valid (e.g.an OPTIONS call). In this API endpoint, you can check the content-length of the request and return an error code back however you wish. This will let your front-end clients that invoke this API know that the file length is exceeded, and there is no reason to actually send the file over to the backend server. (Basically, you will pre-emptively catch this error before NGINX catches it when the file is actually transferred)
Upvotes: 1