Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are Static Files?
3.
Setting Up Express Application
4.
Serving Static Files
5.
Accessing Static Files
6.
Additional Configuration Options
7.
Frequently Asked Questions
7.1.
Can I restrict access to certain static files?
7.2.
What happens if a requested static file is not found?
7.3.
Is it recommended to serve static files using Express in production?
7.4.
Are there any alternatives to Express for serving static files?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Serving Static Files in Express

Author Shiva
0 upvote

Introduction

When building web applications, it's common to include static files such as HTMLCSSJavaScript, images, and other resources. The client must serve these files so the browser can render the web pages correctly. In Express, a popular web application framework for Node.js, serving static files is a straightforward process. 

Serving Static Files in Express

In this article, we will explore the Serving Static Files in Express.

What are Static Files?

Before we dive into serving static files in Express, let's understand what static files are. In web development, static files are files sent from the server to the client without any modifications. These files are pre-existing and don't require any processing on the server side. Examples of static files include HTML files, CSS stylesheets, JavaScript files, images, fonts, and other media files.

Setting Up Express Application

First, we must set up our Express application to serve static files in Express. Assuming you have Node.js and npm (Node Package Manager) installed, follow these steps:

Step 1: Create a new directory for your project and navigate to it in the command line.

Step 2: Initialize a new Node.js project by running the command 'npm init' and following the prompts.

npm initialization

Step 3: Install Express as a dependency by running 'npm install express'.

express installation

Step 4: Create a new JavaScript file, e.g., 'server.js', and open it in a code editor.

With these initial steps completed, we can now start serving static files in our Express application.

Serving Static Files

Express provides a built-in middleware called 'express.static' for serving static files. Middleware functions in Express have access to the request and response objects and can modify them or perform additional tasks. The 'express.static' middleware takes a directory path as an argument and serves the static files from that directory.

To serve static files, follow these steps:

Step 1: Create a new directory in your project called 'public' (you can choose any name) to store your static files.


Step 2: Place your static files, such as HTML, CSS, JavaScript, images, etc., inside the 'public' directory.

folder structure


Step 3: In your 'server.js' file, add the following code before defining your routes:

const express = require('express');
const app = express();
app.use(express.static('public'));

 

In the above code, we require the 'express' module and create a new Express application. We then use the 'app.use' method to register the 'express.static' middleware, passing ‘public' as the directory path. This tells Express to serve the static files from the 'public' directory.


Step 4: Define your routes and other application logic below the middleware code. For example, you can define a route to handle the homepage:

app.get('/', (req, res) => {
	res.send('Hello, World!');
});

 

With these steps in place, your Express application is now configured to serve static files from the 'public' directory.

server file

Accessing Static Files

Once Express serves the static files, you can access them on your web pages using relative URLs. For example, if you have an 'index.html' file inside the 'public' directory, you can include it in your web pages like this:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>BMI Calculator</title>
	<link rel="stylesheet" href="style.css">
</head>
<body>
	<div class="container">
		<h1 class="heading">Coding Ninjas</h1>
		<img src="./coding.png" alt="">
	</div>
	<script src="index.js"></script>
</body>
</html>


Output: 

node server.js
output

In the above code, the CSS file 'styles.css' and JavaScript file 'script.js' are referenced using relative URLs starting with a forward slash ('/'). Express will automatically serve these files from the 'public' directory when the browser requests.

Additional Configuration Options

The 'express.static' middleware in Express also provides additional configuration options to customize the way static files are served. For example, you can set a different base URL path for serving the static files, specify a different directory, enable caching, and more. You can refer to the Express documentation for more details on these options. 

Frequently Asked Questions

Can I restrict access to certain static files?

Yes, you can restrict access to certain static files by using middleware functions before the express.static middleware. For example, you can add authentication middleware to protect sensitive files from being accessed by unauthorised users.

What happens if a requested static file is not found?

If a requested static file is not found, Express will continue to the next middleware in the stack. By default, it will return a 404 Not Found error. You can customise this behaviour by adding error-handling middleware to handle specific cases.

Is it recommended to serve static files using Express in production?

While Express can serve static files efficiently, it is generally recommended to offload static file serving to a dedicated web server or a CDN (Content Delivery Network) for better performance and scalability in production environments.

Are there any alternatives to Express for serving static files?

Yes, there are other web servers and frameworks like Nginx, Apache, and Hapi that can also serve static files efficiently. The choice of server or framework depends on your specific needs and the scale of your application.

Conclusion

Serving static files in Express is a fundamental aspect of web development. Following the steps outlined in this article, you can easily set up your Express application to serve static files. Remember to organise your static files in a separate directory. With Express, you can efficiently deliver static resources to clients and build dynamic and interactive web applications.

 

You may refer to our Guided Path on Code Studios for enhancing your skill set on DSACompetitive ProgrammingSystem Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Happy Learning, Ninja!

Live masterclass