Learning Express Routers: Part 1: Understanding Express Middleware

Learning Express Routers

Express is a popular minimalist web framework for Node.js that provides functionality for creating individual Router objects for responding to particular routes using specified objects.


Understanding Express Middleware

As covered in the Learning Express series, Express provides HTTP request methods for accessing and understanding routes. By specifying a path, a callback function can parse any incoming request data or respond in different ways.

The function use() provides a way to create middleware, software that acts between different layers or systems.

For Express, a middleware can perform actions, parse input, or otherwise act before other actions would take place. It does so by providing the standard Request and Response objects and also a next() function.

As a callback, the next() function will signal that other actions should then happen.

For example, the following code would run before any other actions, acting first as a middleware and then passing control back to anything else. It would also act for all incoming connections.

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

app.use(function (req, res, next) {
  console.log('Time: %d', Date.now());
  next();
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

Stacking Middleware

Multiple calls to use() can be stacked as well. They are then used in the order in which they are defined. For example, the following code would show “First”, “Second”, and “Third” in order for all incoming connections.

For each middleware block, the function next() passes control to the next one.

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

app.use(function (req, res, next) {
    console.log("First");
    next();
});

app.use(function (req, res, next) {
    console.log("Second");
    next();
});

app.use(function (req, res, next) {
    console.log("Third");
    next();
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.