Node.js / Node.js Express Framework

Creating Routes and Middleware in Express

This tutorial focuses on creating routes and middleware in an Express app. You'll learn how to define routes that respond to different HTTP methods and create middleware functions…

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Covers building web applications and REST APIs using the Express framework.

Creating Routes and Middleware in Express

1. Introduction

In this tutorial, we'll delve into the creation of routes and middleware in an Express.js application. Express.js is a popular and robust framework for building web applications on top of Node.js.

The goal here is to equip you with the knowledge needed to define routes that can respond to various HTTP methods and build middleware functions to modify the request and response objects.

You will learn:

  • How to create routes in Express
  • How to create middleware functions in Express

Prerequisites

You should have some basic understanding of:

  • JavaScript
  • Node.js
  • Express.js

2. Step-by-Step Guide

Express Routes

Routes in Express.js define how an application responds to client requests to particular endpoints accessed via HTTP methods.

To define a route, you use app.METHOD(PATH, HANDLER) where:

  • app is an instance of express
  • METHOD is an HTTP request method
  • PATH is a path on the server
  • HANDLER is the function executed when the route is matched

Express Middleware

Middleware functions are functions that have access to the request object, the response object, and the next middleware function in the application's request-response cycle. Middleware functions can:

  • Execute any code
  • Make changes to the request and response objects
  • End the request-response cycle
  • Call the next middleware function in the stack

To create a middleware, you use app.use([path], ...middleware) where:

  • path is optional and defaults to "/"
  • middleware is the middleware function or functions

3. Code Examples

Example 1: Creating a simple route

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

// Route that responds to a GET request at the root '/'
app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});
  • express: we import the Express.js module
  • app: we create an instance of Express
  • app.get(...): we define a route that responds to HTTP GET requests
  • app.listen(...): we start the server on port 3000

Example 2: Creating middleware

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

// Middleware function to log request info
app.use((req, res, next) => {
  console.log(`${req.method} request for '${req.url}'`);
  next();
});

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

app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});
  • app.use(...): we define a middleware function that logs each request's method and URL
  • next(): we call the next middleware function in the stack. If this is omitted, the request will hang

4. Summary

In this tutorial, you've learned how to define routes in an Express app that can respond to different HTTP methods and how to create middleware functions that can modify the request and response objects.

To continue learning, consider exploring:

  • Different types of middleware (application-level, router-level, built-in, error-handling, third-party)
  • More about route parameters and query strings
  • How to organize routes and middleware in larger apps

5. Practice Exercises

Exercise 1

Create a route that responds to POST requests at the path '/data'.

Exercise 2

Create a middleware function that adds a 'timestamp' property to the request object.

Solutions

  1. Route for POST requests:
app.post('/data', function (req, res) {
  res.send('Got a POST request at /data');
});
  1. Middleware function to add a timestamp:
app.use((req, res, next) => {
  req.timestamp = Date.now();
  next();
});

With this middleware, req.timestamp will be available in all following middleware and route handlers.

Keep practicing by adding more routes and middleware to your Express app. Try working with different HTTP methods, paths, and middleware functionality.

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

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Backlink Checker

Analyze and validate backlinks.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

CSV to JSON Converter

Convert CSV files to JSON format and vice versa.

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