In the context of an application lifecycle, middlewares are defined as special functions that have access to the request (req) and response (res) object along with the next() function located in the pipeline.
- app.use((req, res, next) => {
- console.log(req.url); // prints the request url to the console
- next();
- });
The code snippet above depicts a basic way of defining a middleware function in an express application and loading it in the request handling pipeline.
Having put aside the obligation of giving a fancy definition, first up, let's actually get down into what exactly are these middleware functions used for and what are the different ways in which we can inject them in an express application lifecycle.
The code provided below demonstrates the setting up of a basic Express application.
We'll go through it line by line and try to understand how and where the middleware functions fit into the overall scheme of things.
- const express = require("express");
- const app = express();
- const port = process.env.PORT || 3000;
- app.use(express.static(__dirname + "/public"));
- -- in -built express middleware used
- for telling the application from where to serve static files
- app.use((req, res, next) => {
- if (req.url.indexOf("books") > -1) {
- res.status(401).send();
- --exits the pipeline and returns the response back to the browser
- } else {
- console.log(req.url);
- next();
- -- //calls the next middleware/request handler in the pipeline
- }
- });
- app.use((req, res, next) => {
- console.log(`${req.url} route hit at ${new Date().toLocaleDateString()}`);
- next();
- -- //calls the next middleware/request handler in the pipeline
- });
- app.get("/", (req, res, next) => { //request handler for the "/" route
- res.send("root request route..."); //sends the response back to the browser
- next();
- --calls the final middleware in the pipeline
- });
- app.use("/", (req, res) => {
- console.log("From the Terminal middleware...");
- console.log("Doing the post request handling cleanup...");
- });
- app.get("/books", (req, res) => {
- res.send("request route for books");
- });
- app.listen(port, () => {
- console.log(`The server is listening on port ${port}`);
- });

Join the conversation! Your thoughts help the community grow.