How to Serve Static Files with Express and Node.js

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

Overview

When building web applications with Express and Node.js, one often needs to serve static files such as images, CSS files, and JavaScript files. Express, a web application framework for Node.js, includes a middleware function to serve static files easily. This tutorial will guide you through serving static files with Express and Node.js, starting with basic examples and moving to more advanced use cases.

By default, Node.js does not serve files directly; it requires a proper setup to ensure efficient and secure delivery of these files. Express’ built-in middleware function express.static comes into play here, giving us a robust and convenient way to handle such requests.

Getting Started

First, ensure you have Node.js and Express installed. If not, install Node.js from the official website and then install Express using npm:

npm install express --save

Serving Basic Static Files

To serve static files such as images, CSS files, and JavaScript files, include the following code in your Express application:

const express = require('express');
const app = express();

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

app.listen(3000, function () {
  console.log('App listening on port 3000!');
});

In this code snippet, the express.static middleware is used to serve the files located in the public directory. Any file in that directory can be served by specifying its filename in the URL path.

Customizing the Static Files Directory

If you want to serve files from multiple directories or a directory with a different name than ‘public’, simply specify the directory’s path:

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

With the above code, static files located in the ‘assets’ directory are now served at the ‘/static’ path prefix. For example, ‘assets/css/style.css’ is accessible at ‘/static/css/style.css’.

Advanced Configuration

Express and Node.js allow for advanced configuration of how static files are served. You might want to set cache control headers, enable gzip compression, or serve index files when a directory is requested. This can be achieved by passing options to the express.static middleware:

const options = {
  dotfiles: 'ignore',
  etag: false,
  extensions: ['htm', 'html'],
  index: false,
  maxAge: '1d',
  redirect: false,
  setHeaders: function (res, path, stat) {
    res.set('x-timestamp', Date.now())
  }
};

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

The options object above customizes various aspects of how the files are served, including security, performance, and convenience features.

Using Middleware for Security

To increase the security of your application, consider using middleware such as ‘helmet’ to set security-related HTTP headers:

const helmet = require('helmet');

app.use(helmet());
// Static middleware setup goes here
app.use(express.static('public'));

This is just one example of how middleware can be combined with express.static to enhance the functionality and security of your Express application.

Conclusion

In this tutorial, we explored the basics of how to serve static files with Express and Node.js. We covered how to configure Express to serve files from a directory, how to use options for advanced use cases, and how to enhance security with additional middleware. With these techniques, you can efficiently serve static files and create more robust web applications using Express and Node.js.

As with any skill, practice is crucial to becoming proficient at serving static files. Try different configurations and middleware combinations to see what works best for your application. Express’ flexibility offers a powerful toolset for developers, and mastering static file serving is an essential part of that toolkit.

Happy coding!