How to write middleware for Express.Js apps

Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.

Middleware functions can perform the following tasks:

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

Here is an example of a simple “Hello World” Express application.

var express = require('express')
var app = express()

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

app.listen(3000)

Middleware function logger

Here is a simple example of a middleware function called “logger”. This function just prints “logged” when a request to the app passes through it.

var logger = function (req, res, next) {
  console.log('logged')
  next()
}

To load the middleware function, call app.use(), specifying the middleware function. The following code loads the logger middleware function before the route to the root path (/). Here is whole code.

var express = require('express')
var app = express()

var logger = function (req, res, next) {
  console.log('logged')
  next()
}

app.use(logger)

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

app.listen(3000)

You can also read this

Target pseudo-class

This pseudo-class is called target pseudo-class and represents an element...

:target {
    outline: red dotted;
}

How to create a unique list of elements using the Set object

Creating unique lists in javascript is a common task, this...

const list = [1, 2, 3, 5, 2, 5, 7];