Node.js is an excellent JavaScript runtime environment, which you can use to serve entire web assets (static+dynamic) from it. If you are working on a small, experimental project then probably it’s ok, however, if response time is concerned then you must consider using a web server like Nginx in front of Node.js to serve static files. Actually, not just to serve static files but also from a security point of view you should consider Nginx. Lately, I was working on Geekflare Tools (Website SEO & Security Analyzer) where I used Node.js, Socket.io, and was able to improve significant response time by offloading static files from Nginx.

As you can see, when I moved the static files to Nginx on 29th, response time is drastically decreased. So if you are using Node.js to deliver an image, js, CSS, font, etc. then give a thought and consider separating the duties. Let’s take a look at how I did this. This assumes you have Nginx and Node.js installed. Take a backup of the existing configuration before modifying it so you can roll back if things go wrong.

Go to the location where Nginx is installed (default on UNIX based OS like CentOS/Ubuntu would be /etc/nginx) Go to sites-available Create a new file with the following (for easy understanding you can name the file as your domain name)

There is the five crucial block above, let me go through one-by-one.

Upstream – specify the variable as “backend” and give node.js server & port information. In an example, I’ve given localhost:3000 which means I am running node.js on the same server like Nginx with 3000 port number. Server – give the port number, which Nginx should be listening on, and server name as your domain name. Root – the directory from where you want to serve the static files. Location – this is important. I am asking Nginx to try looking for files in the specified directory with root location and if it doesn’t match then go to @backend which is node.js Location@backend – this is generic node.js+websocket.io proxy configuration

Enable the site in /etc/nginx/sites-enabled by creating a symbolic Restart the Nginx and have fun! With the above configuration, I was able to improve response time significantly, and I hope you should too. If you are new to Nginx, then you may be interested in learning how to build a high-performance Nginx server from scratch.

How to Configure Nginx to Serve Static Files for Node js  - 62How to Configure Nginx to Serve Static Files for Node js  - 51How to Configure Nginx to Serve Static Files for Node js  - 40How to Configure Nginx to Serve Static Files for Node js  - 27How to Configure Nginx to Serve Static Files for Node js  - 3How to Configure Nginx to Serve Static Files for Node js  - 95How to Configure Nginx to Serve Static Files for Node js  - 63