How to Serve Static Files from a Node.js App on cPanel
You can serve static files (images, CSS, JavaScript) from your Node.js app using Express's static middleware β but on cPanel it is often faster to let the web server serve them directly, freeing your Node app for dynamic work. Here is how to do both, and when to choose each.
Serving static files from Express
Express can serve a folder of static assets:
app.use(express.static('public'));
Files in public are then served at your app's root. This is convenient and fine for modest assets, but every request still goes through Node.
The faster approach: serve static assets directly
Static files do not need Node's involvement. Where possible, serve large or numerous assets as ordinary static content (from a static folder on your domain), so the web server handles them and your Node app only does dynamic work. This reduces load on your app.
Best of both: a CDN
For images and other heavy assets, a CDN caches and serves them from locations near your visitors, taking the load off your server entirely. Combine this with optimised images for the best performance.
Practical guidance
- Small apps β Express static middleware is perfectly fine.
- Asset-heavy sites β serve static files outside Node and/or use a CDN.
- Always optimise assets regardless of how they are served.
Frequently asked questions
Is it bad to serve static files from Express?
Not for small apps. But every static request then occupies your Node process. For many or large assets, serving them as static content or via a CDN performs better and frees Node for dynamic requests.
How do I reduce static file load?
Optimise and compress assets, cache them, and offload them to a CDN. This cuts both bandwidth and the work your Node app has to do.
Where should uploaded user files go?
Store them outside your web root or in dedicated storage, and serve them carefully. Never allow uploads to execute as code, and validate every upload for security.
Was this article helpful?