Express.js / Middleware in Express.js

Using Built-in Middleware for Static Files

This tutorial covers the use of built-in middleware in Express.js for serving static files, such as HTML, CSS, and JavaScript files.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers the role of middleware in Express and its different types.

Introduction

This tutorial aims to provide a comprehensive guide on how to use built-in middleware in Express.js to serve static files such as HTML, CSS, and JavaScript. Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle.

By the end of this tutorial, you will learn how to:

  • Understand the concept of middleware in Express.js
  • Use Express.js built-in middleware for serving static files
  • Implement middleware for static files in your own Express.js application

To get the most out of this tutorial, you should have a basic understanding of JavaScript, Node.js, and Express.js.

Step-by-Step Guide

What is Middleware?

Middleware functions are those that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. They can execute any code, make changes to the request and the response objects, end the request-response cycle, and call the next middleware in the stack.

Serving Static Files with Express.js Middleware

By default, Express.js does not serve static files like HTML, CSS, and JavaScript. To serve static files, use the built-in express.static middleware function in Express.

Here is an example:

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

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

In the above code, express.static('public') is a built-in middleware function in Express. It serves static files and takes the name of the folder as an argument, from where the static files are to be served (in this case 'public').

Code Examples

Here's an example to serve static files with Express.js middleware:

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

// Serve static files from the 'public' directory
app.use(express.static('public'));

app.listen(3000, function() {
  console.log('Express server is listening on port 3000');
});

In this code snippet, we are using the built-in middleware function express.static to serve static files. This middleware function is called every time the app receives a request. It checks if the request is for a file in the 'public' directory, and if so, it sends that file as the response.

Summary

In this tutorial, we discussed how to use middleware in Express.js to serve static files. We learned that Express.js does not serve static files by default, and we can use the built-in express.static middleware function to serve static files.

To continue learning about Express.js and middleware, you can read the official Express.js documentation, which provides more detailed information and examples.

Practice Exercises

  1. Create an Express.js application that serves static files from a 'public' directory. Test your application by placing an HTML file in the 'public' directory and accessing it in your web browser.

  2. Modify your application to serve static files from a different directory, such as 'assets'. Test your application again to ensure it is serving files from the new directory.

  3. Add a route handler for a specific path (e.g., '/special') and make it serve static files from a unique directory (e.g., 'special-files'). Test your application to ensure it serves files from the unique directory when you access the specific path.

Remember to practice regularly and experiment with different scenarios to get the most out of Express.js middleware for serving static files. Good luck!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

Age Calculator

Calculate age from date of birth.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help