ExpressJS middleware

javascript Oct 20, 2019

how to use middleware in express js application

What is express js

According to the official Documents

"Express is a routing and middleware web framework that has minimal functionality of its own: An Express application is essentially a series of middleware function calls."

what is a middleware

middleware is nothing more than function with three arguments

An Express application can use the following types of middleware:

Application-level middleware

Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions . So in below code snippet, we have a function named log function, and it has three arguments in it

const logfunction =  (req, res, next)=> {
  console.log(`${req.path}   at:${Date.now()}`)
  next()
}

req: the actual request object

res: the actual response object

Next: its a function to pass control to the next middleware function. Otherwise, the request will be left hanging.

now we have defined it, and if we want to use this middleware in our application you need to register this middleware . So to use it globally for all requests we will register in the below way

var app = express()

app.use(logfunction)

and if we want to use it only for a particular route, then we can do it in the following  way

app.get('/someRoute',logfunction, function (req, res, next) {
  res.send('USER')
})

before processing the request, it will call our log function, and if the next function from our middleware is executed then only the function which is returning the response in the above code will be executed

now lets say i have two middlewares one is for logging and one is for Authorize


const authMiddleware = (req, res, next) => {
  const token = req.header('Authorization');
  if (!token) return res.status(400).send('Token Required');
  const payLoad = verify(token, environment.secret);

  req.uid = payLoad['_id'];
  next();
};

So in the above function what we are doing is we are just checking that the user is authenticated and has a valid token if that is true we calling the next function else we are sending 401
now two use two middlewares in express instead of passing a single function we can give an array of middleware functions

var middlewares  = [logfunction, authMiddleware]


app.use(middlewares);


//Or

app.get('/someRoute',middlewares, function (req, res, next) {
  res.send('USER')
})

so first the log function will be called, and then the authentication function will be called

Router-level middleware

Router-level middleware works in the same way as application-level middleware, except it is bound to an instance of express.Router().

var router = express.Router()

Load router-level middleware by using the router.use() and router.METHOD() functions.

var app = express()
var router = express.Router()

// a middleware function with no mount path. This code is executed for every request to the router
router.use('/user/:id', [logfunction, authMiddleware], function (req, res) {
 res.send({status:'done'});
})

Error-handling middleware

Error-handling middleware always takes four arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t need to use the next object, you must specify it to maintain the signature. Otherwise, the next object will be interpreted as regular middleware and will fail to handle errors.

Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature (err, req, res, next)):

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

Built-in middleware

Starting with version 4.x, Express no longer depends on Connect. The middleware functions that were previously included with Express are now in separate modules; see the list of middleware functions.

Express has the following built-in middleware functions:

  • express.static serves static assets such as HTML files, images, and so on.
  • express.json parses incoming requests with JSON payloads. NOTE: Available with Express 4.16.0+
  • express.urlencoded parses incoming requests with URL-encoded payloads. NOTE: Available with Express 4.16.0+

Third-party middleware

Use third-party middleware to add functionality to Express apps.

Install the Node.js module for the required functionality, then load it in your app at the application level or at the router level.

The following example illustrates installing and loading the cookie-parsing middleware function cookie-parser.

$ npm install cookie-parser
var express = require('express')
var app = express()
var cookieParser = require('cookie-parser')

// load the cookie-parsing middleware
app.use(cookieParser())

Neeraj Dana

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Angular, React, React-Native, Vue js, Machine Learning