Languages
[Edit]
EN

Express.js - middleware

0 points
Created by:
Wayne
415

In this article, we would like to show you how to create and use middleware functions in Express.js.

Introduction

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function (next) in express.js application’s request-response cycle.

They are used to:

  • execute any code,
  • modify req and res objects for tasks like parsing request bodies, adding response headers, authentication etc.
  • end the request-response cycle,
  • call the next middleware function in the stack.

Note:

If the current middleware function doesn't end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

Practical example

In this example, we create a simple request tracker that prints every request date in the console and then calls the next() function.

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

app.use((req, res, next) => {
  // get and print current date
  const date = new Date();
  console.log('A new request registered at ' + date);

  // call the next middleware function in the stack
  next();
});

app.listen(3000);

Now when you run the application and send any request (e.g just open http://localhost:3000/) you should get the following result in the console:

A new request registered at Fri Aug 27 2021 16:41:27 GMT+0200 (Central European Summer Time)

Assigning to a specific route

To assign the middleware to a specific route and all its subroutes, you need to specify that route as the first argument of the app.use().

Example:

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

// request tracker
app.use('/users', (req, res, next) => {
  // get and print current date
  const date = new Date();
  console.log('A new request received at ' + date);

  // call the next middleware function in the stack
  next();
});

app.listen(3000);

Now the middleware won't work for localhost:3000/. You need to request any subroute of '/users', only then it will print the time.

Request:

http://localhost:3000/users

Console:

A new request received at Fri Aug 27 2021 16:51:11 GMT+0200 (Central European Summer Time)

See also

References

Alternative titles

  1. Express.js - middleware definition
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join