The concept of routing and middlewares in Express JS
By: Bolu Akinsefunmi
Tags: Middleware, Expressjs, Route, JavaScript

Have you ever encountered the word “routes”?

As defined by Marriam Webster dictionary, a route is a traveled way which is also said to be a means of access.

After comparing definitions from different dictionary, I will state a “route” to be “a path that leads to a destination”, imagine trying to move from your house to the nearest bus stop, the bus stop is your destination while the road that links the house to the bus stop and vice versa is the “route”

In web development a “route” is an endpoint or a path, used by a client to access unique resources and perform specific actions on the web server.

Why are routes created?

The computer is just an electronic machine, the instructions given to it will determine how intelligent this machine can and will be.

Routes are created so that the web application will know how to interpret and respond to each and every HTTP request made by the client

Imagine waking up on a beautiful Monday morning to discover that your street is flooded, and there is no route to the bus stop, your destination becomes inaccessible.

In the same vein, resources on the server will be inaccessible by client if routes do not exist.

How to create routes

Before you think of creating routes with express JS, you must have the following requirements:

1. node js runtime environment

2. node package manager

3. express js framework

The syntax for defining a particular route takes the following structure:

app.METHOD(PATH, HANDLER);

— Where app is an instance of express

— METHOD is the type of request

— PATH is the path on the server HANDLER is the callback function to be executed if a client accesses the route

Create a file called route.js and enter the codes below

const express = require(“express”) //imports the framework

const app = express(); //creates an instance of the framework /** * creates a route to server_name/welcome for GET and POST request */ app.get(“/welcome”, (request, response) => {

response.send(“Welcome!”);

}); app.post(“/welcome”, (request, response) => {

const postedName = request.body.name;

response.send(`You posted ${postedName}!`);

}); app.listen(3000); //server port

For more details about routing, see the official routing guide.

What middlewares are in express?

Middlewares can be said to be the middleman between a request and a response they act as bridges between requests and responses, a typical express application is comprised mainly of middleware function calls.

A particular middleware function will have access to the request object, response object, and the next middleware function in any request-response cycle

Middleware functions can execute any code but its main task is to manage and modify request and response objects, terminate a request-response cycle and if not, send the baton of control to the next middleware.

There are different types of middlewares available for use in express application and they include:

1. Application-level middleware

2. Router-level middleware

3. Error-handling middleware

4. Built-in middleware

5. Third-party middleware

Why Middlewares are important

While standing as a middleman between the request from the client and response from the server the middleware can parse the request in an acceptable form for the server to handle and modify the response to be a favorable one for the client

User inputs are know to cause commotion and they should never be trusted, middlewares can help to sanitize user inputs and in case something goes wrong, middlewares can help to handle the errors

Even for the creation of a route the handler callback function is an application-level middleware system so technically there will be no express app without middlewares

How to create and use middlewares

Before you can create and use middleware you have to install:

1. node js runtime environment

2. node package manager

3. express js framework

Create a file called middleware.js and enter the code below

const express = require(“express”) //imports the framework

const app = express(); //creates an instance of the framework /** * creates a middleware to log every request object to the console */ app.use((req, res, next) => {

console.log(req);

next();

}); /** * creates a route responding to GET request on “/” and “/another-route” */ app.get(‘/’, (req, res, next) => {

res.send(‘Welcome Home’);

}); app.get(‘/another-route’, (req, res, next) => {

res.send(‘Welcome to another route);

}); app.listen(3000); //server port

For more details about middleware, see the official middleware documentation.