Don’t serve static files with NodeJS
Huy
937

While this seems nice in theory, if your server is properly configured, the only thing Nginx should be doing is proxying port 80/443 requests to the port your Nodejs app is running on.

For the purpose of security (and this CRITICAL) you Nodejs app should be run as a non-privileged user, meaning requests sent by this user for static files to Nginx would be permission denied, as this would effectively be executing requests above that user’s perms levels.

Express doesn’t actually run as a service (as far as Nginx is concerned) and thus it would actually be your application server (Nodejs) that would be requesting the static files, as Nodejs runs as a service run by, again, a different user than root, but one with perms to access all app-related files, and yet a different user from the non-privileged user ultimately running the app.

Serving static files, therefore, should really only be done by Nodejs itself; if you use Express to handle this request, that’s fine, but not required. If you need a different thread/process to handle this, Nodejs and Nginx already play well as being harmoniously asynchronous but you could always use Async or Fibers, which would still reside within your app.

Your idea is not wrong, it just means setting up a server environment that is horribly insecure.

If your app is compromised, or easier, your static files can be compromised, a hacker can easily use that to pwn your server.

You’re better off making the requests in the app; Nginx will decide how to handle serving them.

Like what you read? Give Christopher Shaffer a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.