Serving static files

Build web apps with NodeJS & Express

🕑 This lesson will take about 15 minutes

Static files are files that are downloaded to the client’s device and don't change when your application is running. Examples of these include CSS stylesheets (CSS files containing code that sets the theme, layout and style of a web page), JavaScript files containing client-side JavaScript code that runs on the client’s device, images, videos, etc.

In this lesson, we will use a static CSS file to create a basic theme for our app’s homepage. We will serve this static file to the client using the express.static function. Firstly, you will need a folder/directory to store your static assets such as CSS files. If you didn’t already do this in the lesson on sending responses to the client, create a new folder/directory within your app folder called “public”. The “public” directory will store some static assets for our web app such as CSS files.

Screenshot of the app project's folder/directory structure with a new directory called "public" inside the app directory.

Go to your index.js server code file and add the following line of code to specify the directory for your static files. This line should be added near the top of your code but after the express and app constants.

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

Your index.js (server code) file should now look like this:

Now, create a new CSS file in the ‘public’ directory called ‘style.css’. Add some CSS code to the file to create a basic theme for your website. If you are not familiar with CSS code, it’s a good idea to review the course on HTML & CSS. As an example, the following CSS code just sets a background colour and font to use for the text.

body{
background-color: rgb(107, 143, 208);
font-family: Arial;
}

As shown in the screenshot below, the ‘style.css’ file is stored in the ‘public’ directory.

Screenshot of code editor showing a CSS file stored in the public directory and some CSS code in that file

Here is the sample CSS code:

Now all we need to do is tell the EJS template file that we want to use the code in this this static CSS file for our web page’s theme. Go to the index.ejs file and add the following line of code in the <head> section of the HTML code.

<link rel="stylesheet" href="style.css" type="text/css">

Here is the complete code for the index.ejs template file:

Restart the server and refresh the home page of the app in your browser. The home page should now use the theme specified in your static style.css file.

If you wish to create more static directories, you can use the express.static function multiple times in your server code. For example, if you want a separate directory for images, you can add the line of code app.use(express.static('images')); to your server code (index.js file).

Next lesson: An overview of HTTP methods