Serving Static Files in Express

Learn via video courses
Topics Covered

Overview

This article will cover the topic of Serving static files in Expressjs, but before going deep into the details, let's take a brief look at what this topic involves.

Serving static files in Expressjs: ExpressJS provides a built-in middleware function called express.static() that allows you to serve static files in your application. This middleware takes a directory path as an argument and serves any files in that directory at their respective URL paths. This makes it easy to serve files such as images, CSS files, and client-side JavaScript files to the client without having to write custom code. Simply specify the directory path using express.static() and mount it to the root path of your application using app.use().

So let us now begin with the main agenda of the article, Serving static files in Expressjs.

Introduction

The most famous framework for Node.js to build web applications is ExpressJs, which is very efficient and user-friendly to create APIs and web applications. For creating web applications, we are required to do common tasks, one of which is serving static files like JavaScript files, images, and stylesheets. In this context, static files refer to files that are stored on the server and sent to the client as-is, without any server-side processing.

A built-in middleware function is provided by Express called express.static() that allows you to serve static files from a directory. This middleware function takes one argument, which is the name of the directory where your static files are stored.

Syntax:

The syntax of express.static is as follows:

Explanation:

Here, root is the root directory from which the static assets will be served. This is a required parameter. The options parameter is an optional object that can be used to configure the behavior of the middleware. The following options are available:

  • maxAge: The maxAge option of express.static sets the value of the max-age property in the Cache-Control header of the response. This property determines the length of time for which the browser should cache the static assets. By default, the value is set to 0, which indicates that the browser should not cache the assets.
  • etag: determines whether to generate ETags for the response. ETags are used by the browser to check if the asset has been modified since it was last requested. The default value is true.
  • lastModified: determines whether to set the Last-Modified header for the response. This header specifies the date and time when the asset was last modified. The default value is true.
  • immutable: determines whether to set the immutable property in the Cache-Control header of the response. This is used to indicate that the asset is immutable and will never change. The default value is false.

Serving Static Files in Express

Now let us look in steps at how we can serve static files in Express.

Setting up Express

Setting up Express can be done by following these steps:

  1. Install Node.js: It is a prerequisite to install Node.js. You can download and install Node.js from the official website: NodeJs.
  2. Create a new project directory: Open your terminal or command prompt and create a new directory named express-with-static-files for your project. You can use the following command:
  3. Navigate into your new project directory: In the terminal or command prompt write the following command:
  4. Initialize npm: Now initialize the node package manager in your directory, through which you can install and use different dependencies. A package.json file will be created through which you can access your dependencies. run the following command to initialize a new npm package:
  5. Install Express: Use the following command to install Express as a dependency for your project:
  6. Create an app.js file: Create a new file called app.js in your project directory. This is where you will write the code for your Express application.
  7. Modify your start script in your package.json file by including node app.js
    This will enable you to start your Express server using the npm start command in your terminal.

Structuring Your Files

Now, you need to create a public directory in your main directory to store all the client-side files and add a home.html file and a dog.png image in it. The structure of your files would look like this:

Now after setting up all your files, let us create an express server.

Creating Your Express Server

Creating your express server can be done by following these steps:

  1. Set up your Express app: In your app.js file, start by requiring the Express module and creating an instance of the Express application:
  2. Define your routes: You can define routes in your Express app using the app.get() method. For example:
    This defines a route for the root URL that will send the string Hey Developers! as the response.
  3. Start your server: Finally, you can start your Express server using the app.listen() method. For example:
  4. This starts the server on port 3000 and logs a message to the console when the server is ready.

With these steps, you should now have a basic Express server set up and ready to go.

Serving Your Static Files

A built-in middleware function is provided by Express called express.static that allows you to serve static files from a directory. This middleware function takes one argument, which is the name of the directory where your static files are stored. Here's an example of how to use express.static to serve a directory named public:

The code in the app.js file will be as follows:

Output:

Explanation:

In this example, the express. static middleware function is added to the application using app. use(). The argument passed to express. static is the name of the directory where the static files are stored, in this case, public.

Now, any files in the public directory can be accessed by the client by simply requesting the file's URL. For example, if you have an HTML file named home.html in the public directory, you can access it from the client by requesting the URL http://localhost:3000/home.html.

It's important to note that the express. static middleware function should be added before any other middleware functions that handle routing. Otherwise, the static file request will never reach the middleware function and will result in a 404 error.

Now, your backend part of the project is finished, let us now focus on the client side of the project.

Building Your Web Page

Now, Go to your public directory and find the home.html file you created. Add body and image components to the file:

home.html

Explanation:

  • In the above HTML code, we have a heading tag and an image tag inside the body.
  • Inside the image source we have given dog.png, as we know the public directory is been served in the express server, so we can use the image file name present in the public directory directly inside the image source tag.

Running Your Project

Now in your terminal run the express server:

Output:

Now go to your default web browser, and direct to http://localhost:3000. Your project will appear:

web browser dog

Advanced Use Cases

Now let us look at some advanced use cases of serving static files in expressjs.

Multiple Static Directories

While creating web applications, we might come to a situation where we need to serve multiple static directories in our express application. We can do that very easily, we just have to add app. use(express. Static("{directory}")) multiple times, where the directory name which we want to use as a static file should be in the place of {directory}. Let us look at an example to get a more clear understanding:

Example:

Abstract: Let us take the above example where we used the public directory serving as the static file. The public directory consisted of an HTML file termed a home.html file, and an image file termed dog.png. Now, we want to store the image in a separate directory, let's say the images directory, and we have stored the dog.png image in that. The structure of your files would look like this:

Now to make the images directory also serve as a static directory, we just need to do some changes in the express server file which is the app.js file.

Code:

That's it! Now go to your default web browser, and direct to http://localhost:3000. Your project will appear.

Virtual Path Pref

In Express.js, you can use a virtual path prefix to serve static files from a specific directory. This is helpful if you wish to serve static files from a location other than your website's root directory.

Here's an example of how to serve static files from a directory with a virtual path prefix:

Explanation:

In this example, the express. static() middleware serves static files from the public directory, but only when requested using the /static URL path. The __dirname variable is used to specify the absolute path to the public directory, and the + operator is used to concatenate the virtual path prefix /static to the absolute path.

Now, if you have a file named home.html in the public directory, you can access it from the browser using the URL path/static/home.html. The server will respond with the contents of the file and set the appropriate MIME type based on the file extension.

Conclusion

In this article, we learned about Serving static files in Expressjs. Let us recap the points we discussed throughout the article:

  • The most famous framework for Node.js to build web applications is ExpressJs, which is very efficient and user-friendly to create APIs and web applications.
  • We are required to do common tasks, one of which is serving static files like JavaScript files, images, and stylesheets. static files refer to files that are stored on the server and sent to the client as-is, without any server-side processing.
  • A built-in middleware function is provided by Express called express.static() that allows you to serve static files from a directory. This middleware function takes one argument, which is the name of the directory where your static files are stored.
  • The steps of serving static files in expressjs are setting up express, structuring your files, creating your express server, serving your static files, building your web page, and running your project.
  • While creating web applications, we might come to a situation where we need to serve multiple static directories in our express application. We can do that very easily, we just have to add app. use(express. Static("{directory}")) multiple times, where the directory name which we want to use as a static file should be in the place of {directory}.
  • In Express.js, you can use a virtual path prefix to serve static files from a specific directory. This is helpful if you wish to serve static files from a location other than your website's root directory.