Middleware in Express nodejs

Source:ButterCMS

Previously, we learned about the fundamentals of Express. In this article, we will learn about middleware in Express NodeJS library and how to apply them in our code

The Basic Idea: What’s Middleware?

In layman terms, a web server is a function that inputs a request and outputs a response. Here, middlewares are functions executed in the middle after the incoming request, which then produces an output. This output could either be

  • the final output, or
  • used by the next middleware until the cycle is completed.

This in turn, means that we can have more than one middleware function and they will be executed in the order they are declared. In other words, this is a chain-like order.
Since they are executed in a chain-like order, we can represent this diagrammatically like so:

In this code execution, middleware A is called first, therefore it will run first. After that, the program will execute middleware B, and so on and so forth.
As they are part of Express framework, they have access to the request object(req )and response object(res ), and the next function in the application response cycle.
Here, the next function will execute the next middleware in the chain when invoked.
Moreover, bear in mind that an Express application is essentially a series of middleware calls.

Basic Middleware Syntax

To declare a simple middleware function,

const MiddleWareFunction1 = function(req,res,next)=> {
//code to be executed , main logic located here, then 
next(); //tell the program to go to the next function call.
})

Using Middleware

Now that we have built our middleware method, we now have to call it:

app.use(middlewareFunction)

Since Express uses middleware in routing methods, we can even use it like so:

app.use(route, middlewareFunction);

This means that middlewareFunction() will be called if user navigates to route path.
In the next section of this guide, we will cover on basic examples which will help you understand middleware in Express.

Simple usage

Hello World in middleware
Here’s a simple example:

//step 1: create the function
function sayHello(req,res,next) {
  console.log("Hello World"); //log out to the console
  next(); //proceed to the next function
}
//step 2: Use it as middleware:
app.use(sayHello); //here, we haven't specified a route.
//this means that the sayHello method will run just before every request

app.get("/",(req,res,next)=> {
  res.send("Get request: hello, world");
});
app.listen(3000);

This will be the result:

requestTime function
Remember when I said that middleware functions have access to the URL’s request and response properties? We can add properties to these objects and then pass them on to next middleware like so:
Here is a simple example to show date and time of when a request is sent:

//create a function
var requestTime = function (req, res, next) {
  //get the current date and assign it to the req.requestTime variable
  req.requestTime = Date.now();
  next();
};

app.use(requestTime);

app.get("/", function (req, res) {
  var responseText = "Hello World!<br>";
  //get the value of req.requestTime that we declared earlier
  responseText += "<small>Requested at: " + req.requestTime + "</small>";
  res.send(responseText);
});

This will be the output:

Configurable Middleware

Let’s say your middleware function takes up many lines of code. Thus, you want it to be in another module. You can use module.exports . This also makes your middleware configurable. To learn about module.exports , click here.
An example of this can be:
In a file my-middleware.js

module.exports = function (options) {
  return function (req, res, next) {
    // Implement the middleware function based on the options object
    next()
  }
}

Next, write the following code in main.js:
In file main.js

var mw = require('./my-middleware.js')
app.use(mw({ option1: '1', option2: '2' }))

Middleware substacks
You can even load multiple middleware functions within app.use to save more time and make your program look less complex.

app.use(
  "/", //run the first function
  (req, res, next) => {
    console.log("Reached first substack");
    next();
  }, //now run the second function
  function (res, req, next) {
    console.log("reached second substack"); 
    next();
  }
);
app.get("/", function (req, res) {
  res.send("Hello World");
});

Conclusion

Middleware functions are a crucial topic to learn when it comes to Express. Not only are they easy to learn, they also help your code be cleaner and more readable.
Thank you so much for reading! Happy coding!

Scroll to Top