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

The :valid CSS pseudo-class

The :valid CSS pseudo-class represents any  <input> or other <form> element whose...

input:valid {
  background-color: powderblue;
}

Simple REST API with ExpressJS

Express is a minimal and flexible Node.js web application framework...

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));