How to Serve Static Files (CSS, JS, Images) in Express JS?

Last updated on: by Digamber
Today we are going to learn the most crucial topic among web developers is how to serve static files like images, CSS, JS (javascript) in Express js.

Express js is fast, flexible, robust, minimalist web framework for Node.js. Express js allows us to create powerful RESTful APIs using the HTTP modules and connect components. It offers several middleware functions like (req, res, next) to build a high level of web applications.

Serving Static Files in Express.JS

Express makes serving static files extremely easy. We are using Express.js 4.17.1 version to serve static files such as images, CSS, JS using the built-in express.static middleware function.

express.static(root, [options])

The root parameter associated with a root folder from where static assets are being served. The above middleware method defines the file to serve by including the req.url along with the declared root folder. This static method doesn’t return 404 response when the data is not found; instead, it triggers the next() middleware. Let us check out below how we can serve static files using Express static method.

Setting up Express Server

Create a project folder and enter into the project directory by using the following command:

mkdir express-static-app && cd express-static-app

Create a specific pacakge.json file, and this file contains the project’s NPM dependency information.

npm init
# {
#   "name": "express-app",
#   "version": "1.0.0",
#   "description": "How to serve static files in Express.js",
#   "main": "server.js",
#   "scripts": {
#     "test": "echo \"Error: no test specified\" && exit 1"
#   },
#   "author": "Digamber",
#   "license": "ISC"
# }

Create a folder by the name of public, in this folder we will keep all our static assets. Run the command from the root of the project.

mkdir public

Next, Install Express middleware inside our project folder:

npm install express

Create server.js file inside express app directory.

touch server.js

Inside the server.js file add the following code. This code will help us to create a basic express server with PORT => 8080.

// server.js
const express = require('express');
// Define Express App
const app = express();
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log('Server connected at:',PORT);
});

Then, type command to start the Express server.

node server
# Server connected at: 8080

Serving Static Files via Express Middleware

We have already created the public folder from where we will serve static files. In this step we are going to use express.static middleware to serve static assets from the public folder.

We will create images, CSS, JS folder and index.html file within the public folder and serve directly from public folder.

Run command to create file and folder inside the public folder:

mkdir css && mkdir images && mkdir js && touch index.html

Add the express.static method inside the server.js file.

// server.js
const express = require('express');
// Define Express App
const app = express();
const PORT = process.env.PORT || 8080;
// Serve Static Assets
app.use(express.static('public'));
app.listen(PORT, () => {
    console.log('Server connected at:', PORT);
});

Now, create style.css file inside public/css folder and add the given below code:

body { 
  background-color: blue
}

Create index.js file inside public/js folder and include the following code:

// index.js
function multiply(x, y)
{
  return x + y;
}
console.log(multiply(5, 6));

Create index.html file inside public folder and include the following HTML template code:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>The HTML5 Template</title>
</head>
<body>
<h1>Code is being served via Express engine!</h1>
</body>
</html>

At last, inside the public/images keep an image to serve via express static method.

You can check out on the following assets, just restart the express server.

PathURL
public/imageshttp://localhost:8080/images/code-guy.jpg
public/csshttp://localhost:8080/css/styles.css
public/jshttp://localhost:8080/js/index.js
publichttp://localhost:8080/index.html

Define Multiple Static Directories in Express

Express allows defining multiple static assets directory to serve the static assets. It is pretty simple and straightforward, define multiple express.static middleware function in server.js file.

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

We have defined two folders public and images in above code. Express searches through in the same order we define express.static middleware methods. We need to create the virtual path prefix to serve the files via express.static middleware function.

// Virtual Path Prefix '/static'
app.use('/static', express.static('public'))

Here, ‘/static’ is the virtual path prefix, now you can access static assets via following paths.

URL
http://localhost:8080/static/code-guy.jpg
http://localhost:8080/static/styles.css
http://localhost:8080/static/index.js

Conclusion

Finally, we have completed how to serve static files (CSS, JS, Images) in Express JS tutorial with examples. I hope you enjoyed learning from this tutorial. Thanks a lot for reading this tutorial, if you have reached here that means you have server your static files with Express.js successfully if you are looking for express documentation, click here to visit the official express site.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.