Express.js Middleware Tutorial

Developers who are new to Express often get confused with the difference between route handler and middleware. Therefore they also get confused with the difference between app.use(), app.all(), app.get(), app.post(), app.delete() and app.put() methods.

In this tutorial I will explain the exact difference between a middleware and route handler. And also how to use the app.use(), app.all(), app.get(), app.post(), app.delete() and app.put() methods correctly.

Route Handler

app.all(), app.get(), app.post(), app.delete() and app.put() methods are all used to define routes. A route is used to handle a HTTP request. A route is a combination of a path and callback, which is executed when a request’s path is matches. The callback is called as the route handler.

The difference between app.all(), app.get(), app.post(), app.delete() and app.put() methods is that they handle different types of HTTP requests. For example: app.get() handlers only GET requests whereas app.all() can handle GET, POST and so on.

Middleware

A Middleware is a callback that sits on top of the actual request handlers. It takes the same parameters as a route handler.

To understand middleware let’s take an example site which has a dashboard and profile page. To visit these pages the user must login. Requests to these pages are also logged. Here is how the route handler for these pages would look like:

var app = require("express")();

function checkLogin(){returnfalse;}

function logRequest(){ console.log("New request");}

app.get("/dashboard",function(httpRequest, httpResponse, next){

logRequest();

if(checkLogin()){ httpResponse.send("This is the dashboard page");}else{ httpResponse.send("You are not logged in!!!");}});

app.get("/profile",function(httpRequest, httpResponse, next){

logRequest();

if(checkLogin()){ httpResponse.send("This is the dashboard page");}else{ httpResponse.send("You are not logged in!!!");}});

app.listen(8080);

Here the problem is that there is a lot of repeating code i.e., we had to logRequest() and checkLogin() function calls multiple time. This also makes it difficult to update code. So to deal with this problem we can write a common route for these two paths. Here is the rewritten code:

Here is the code looks a lot cleaner and is easier to maintain and update. Here the first two defined route handler are called as middleware because they are not handling the request rather responsible for pre-processing of the request.

Express provides us app.use() method which is specifically used to define middlewares. app.use() method may seem similar to app.all() but there are a lot of differences between them which makes app.use() perfect for declaring middlewares. Let’s see how app.use() method works:

app.use()

Here are the difference between app.use() and app.all():

Callback

app.use() takes only one callback whereas app.all() can take multiple callbacks.

Path

app.use() only see whether url starts with specified path where app.all() will match complete path.

next()

next() call inside a middleware invokes the next middleware or route handler depending on whichever is declared next. But next() call inside a route handler invokes the next route handler only. If there is a middleware next then it’s skipped. Therefore middlewares must be declared above all route handlers.

First of all be consistent of writing your semicolons, I know JavaScript has ASI, but when trying to teach people JS while writing blogposts, be 100% correct, every time.

Secondly, please do not write JavaScript in a C-like manner ({ – on the next line) this fucks up when you are trying to return objects, and a lot of beginning JavaScript programmers (especially coming from C-like languages) have trouble understanding why.

Content-wise this blogpost is correct, but be aware that on “style” level this needs a lot of work.

To create code blocks or other preformatted text, indent by four spaces:

This will be displayed in a monospaced font. The first four
spaces will be stripped off, but all other whitespace
will be preserved.
Markdown is turned off in code blocks:
[This is not a link](http://example.com)