Fix: Node & Express Can’t Load Static Files

Updated: December 28, 2023 By: Guest Contributor Post a comment

Understanding the Issue

When developing a Node.js application using Express, you might encounter an issue where static files such as CSS, JavaScript, or images fail to load. This usually occurs because Express.js does not serve static files by default. You need to explicitly tell the server where to look for these files.

Steps to Fix the Issue

1. Specify Static Directory: Use express.static middleware to serve static files. For example, if your static files are in a directory named public, add the following line to your Express app:

app.use(express.static('public'));

2. Correct File Paths: Ensure the paths you use in your HTML match the file structure within your specified static directory.

Code Example

// Require express
const express = require('express');
const path = require('path');

// Initialize express app
const app = express();

// Serve static files from 'public' directory
app.use(express.static(path.join(__dirname, 'public')));

// the rest of your app logic goes here

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

Alternative Methods

1. If you have static files in more than one directory or if you want to specify a virtual path prefix, you can use:

app.use('/static', express.static('public'));

2. In this case, your file URLs will start with ‘/static’ (e.g., http://localhost:3000/static/css/style.css).

Another approach, if your static files are on a different server or Content Delivery Network (CDN), is to make sure the URLs in your HTML point to the correct remote locations.

Note

Remember to restart your Node.js server after making changes to your code.