THE CONCEPT OF ROUTING AND MIDDLEWARE IN EXPRESS.js

Edet Noah
The Startup
Published in
5 min readNov 12, 2020

As a server-side developer, it is however necessary to understand the concept of routing and middleware. In this article we'll emphasize more on Express.JS (a back-end web application framework for Node.js).

SO WHAT ARE ROUTES?🤔💭

Routes refers to paths for which data travels on a network. It can also be said to be a way taken in getting from a starting point to a destination.
So let's think of routes this way, if my starting point is “A” and my destination is “B” then the path to which I follow from my starting point “A” to get to destination “B” is my route.

Having known what routes are….

WHY ARE ROUTES CREATED?💭

Routes are created so as to determine the data that would be delivered given any URL.
For instance, when we type in www.google.com in a browser, the response we get is the data which has been programmed by a developer and then it gets delivered to the URL www.google.com.

A Demonstration Of How Routes Are Created In Express.JS

LINUS TOLVARDS will say… “TALK IS CHEAP. SHOW ME THE CODE” 😂

First of all let’s create a folder that houses our code. To do so
open up your terminal and get your fingers to work.😊

1. cd Documents 👉(This will take you to document directory, if you're already there jump to step 2).
2. mkdir my-first-route 👉(This will create a new directory called “my-first-route” inside your Document directory)
3. cd my-first-route 👉(This will take you to “my-first-route” directory)
4. touch app.js (This will create a new file called “app.js” in “my-first-route” directory)
6. npm init 👉(This will let you setup your npm package)
7. npm install express — save 👉(This will install “express” and save it as a dependency in this project)

Having typed in the command, we should have our files and folders in this structure

The Folder Structure
Folder Structure

so let's keep it going …
Type in these codes in our app.js file

const app = require("express")();const PORT = 2000;app.get("/", (req,res) =>{res.send("welcome to my homepage!!!!!!");console.log("welcome page");});app.listen(PORT, ()=>{console.log(`APP IS RUNNING ON PORT ${PORT}...`);});
Writing Our Route

Now to start our server, type in
node app.js in the terminal and hit enter

Our server is up and running

open up your browser and type in
http://localhost:2000/

CONGRATULATIONS… YOU’VE SUCESSFULLY CREATED A ROUTE🤗

MIDDLEWARE IN EXPRESS

Express middleware are functions that execute in-between the lifecycle of a request to the Express server and which also have access to req and res methods.

const app = require("express")();const PORT = 2000;app.get("/", (req,res) =>{res.send("welcome to my homepage!!!!!!");console.log("welcome page");});app.listen(PORT, ()=>{console.log(`APP IS RUNNING ON PORT ${PORT}...`);});

So from the code above, we can say the function with (req and res) is a middleware..

let’s see middleware in Express as a bridge between one layer and another.

Okay, that’s the basis.. lets dive in

Lets create our own middleware, like we already know by now that a middleware is a function that has access to req and res method.

from the code above we’ve created a function logger which has access to the req and res methods.. YEAH that’s a middleware!

Okay, now we have to tell Express we want to make use of that middleware, to do so we make use of app.use('middleware_name') in this case our middleware name is ‘logger’. So its going to be app.use(logger)
WE DON”T HAVE TO CALL IT AS A FUNCTION app.use(logger()). Take note of that.

let’s start our server and see what’s happening

Wow… nothing is displaying

let’s check our terminal

We’re getting respond from our logger middleware but nothing from our “/” route and we are expecting a respond from that route because we are in there.. So what’s happening here?

Express don't know what to do after that respond, we have to tell it! and to do so we make use of the “next” function in Express and what this does is that
It tells Express to run the next middleware.

Next function in express executes the middleware succeeding the current middleware.

In our logger middleware we have to pass in next as a parameter so we can have access to it by calling it as a function in our logger method.

const app = require("express")();const PORT = 2000;app.use(logger);app.get("/", (req, res) =>{res.send("welcome to my homepage!!!!!");console.log("welcome page");});function logger(req, res, next){console.log("log");next()}app.listen(PORT, ()=>{console.log(`APP IS RUNNING ON PORT ${PORT}...`);});

So let’s start our app and visit localhost:2000

Yeah, so now everything works as expected.

MIDDLEWARE RUNS IN THE ORDER THAT WE DEFINE THEM

Here is a demonstration…

From this, we can see that our welcome page was render first before our logger middleware unlike our previous code where we have our logger middleware before our welcome page, and also notice where the next function is…
Our logger middleware don’t need the next function because we are not running any middleware after it.

MIDDLEWARE SPECIFIC TO A SINGLE ACTION

This type of middleware can be passed directly to a function without it being declared globally like we did earlier.

So here is a demonstration..

const app = require("express")();const PORT = 2000;app.get("/data", checker, (req, res) =>{res.send("Data page");console.log("Data page");})function checker( req, res, next){console.log("i am the checker");next()}app.listen(PORT, ()=>{console.log(`APP IS RUNNING ON PORT ${PORT}...`);});

The code runs as intended.

With this, I hope you’ve been able to grasp the concept of routing and middleware in Express.js

Happy coding😊😊

--

--