Article, NodeJS

How to Use Node.js Express Middleware in your Web Application?

 March 15, 2020

By  Rangel Stoilov

Middleware plays an important role when building Node web applications using Express framework. Simply put, you cannot build an Express application without incorporating middleware. So, the possibility is, knowingly or unknowingly, you have used middleware in your Express applications before. Then, it’s high time that you get to know what exactly middleware is and how to get the maximum advantage out of it.

What is Express Middleware?

Middleware is a function that runs in between two other functions. In Express, middleware is run in the time between the server receiving a request and the request approaching its route handler. Middleware function accepts three basic inputs: HTTP request and response objects, and the next middleware function that is going to be called.

function middlewareExample(req, res, next) {
	if (req.someParameter === 1) {
	} else {
		res.send("Can't continue further")

As the example shows, middleware can be used to determine whether the request should be passed on to the next middleware. If not, an appropriate response is sent, ending the lifetime of the request.

Where should Express Middleware be Used?

In general, middleware can be used to carry out any process that has to be completed before finally passing the request to the route handler. However, there are three main occasions where middleware is commonly used.

1. Authentication & Authorization

Express middleware can be used to check whether the requesting user has permission to access the route handler. If the user does not have permission, the request is terminated and a message denying access is sent. Otherwise, the request gets permission to proceed to the next step.

function verifyUser(req, res, next) {
	let token = req.headers['x-access-token']
	if (!token) {
		return res.status(403).json('Log in to continue')

	jwt.verify(token, config.secret, (error, decoded) => {
		if (error) {
			return res.status(403).json('Invalid token')
		} else {

2. Error Handling

Error handling middleware can be used in Express to handle any unhandled error that occurred during the execution. This type of middleware accepts an additional argument, error, along with the previous three arguments.

function handleUnhandledError(err, req, res, next) {
	if (err) {
		res.status(500).send('An error occured')
	} else {

Middleware can then handle the error in an appropriate manner.

3. Logging

Express middleware can be used to logging user requests. Before directing the request to the route handler, the user’s request is logged to keep a record of the user’s access history.

function logUserRequest(req, res, next) {

How to Use Express Middleware?

There are several ways to use middleware in an Express application.

The simplest method is using the middleware before all the route handlers in your application.

const app = express()
const middleware = require('/middleware')


app.get('/firstRoute', firstRouteHandler)
app.get('/secondRoute', secondRouteHandler)

In this example, the middleware is used before both ‘firstRoute’ and ‘secondRoute’ route handlers.

You can also introduce a route handler specific to a particular route as shown in the following example.

app.get('/firstRoute', middleware)
app.get('/firstRoute', firstRouteHandler)
app.get('/secondRoute', secondRouteHandler)

In the above method, the middleware is only used on requests coming to the ‘firstRoute’ route handler.

The final method to use middlewares is using them inside the route handler before the handling function.

app.get('/firstRoute', middleware, firstRouteHandler)
app.get('/secondRoute', secondRouteHandler)

Here, the middleware is used inside the ‘firstRoute’ route handler and it applies only to the requests coming to this endpoint.

You can also ‘chain’ middleware functions. Middleware chaining indicates directing the request from one middleware function to another. Chaining can be implemented in any of the three ways shown in the previous examples.

app.get('/firstRoute', middleware1)
app.get('/firstRoute', middleware2)
app.get('/firstRoute', middleware1, middleware2, firstRouteHandler)

Here, when the next is called inside the middleware1 function, middleware2 starts its implementation.

Built-in and Third-party Middleware

In addition to defining your custom middleware, Express applications can use built-in or third-party middleware. Here, you can see examples of such usage.

const bodyParser = require('body-parser')

app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.static(__dirname + '/public'))


Rangel Stoilov

Hello! My name is Rangel and I have been a web developer for 8 years now. First I have started with Dreamweaver back in the days and went through Wordpress as a simple way to create websites. After that I wanted to go further in the web development so I started learning different programming languages such as C#, Java & JavaScript. I have a major in Java with Spring Framework and now I am pursuing to deepen my knowledge in different JavaScript frameworks. I also have a passion for Solidity and Smart Contracts as well as the Truffle Framework. I have also dived in the entrepreneurial spirit with Amazon publishing and trading on the Forex market as well as creating automated systems for trading.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}