How To Use ExpressJS Router middleware

How To Use ExpressJS Router middleware

¡

3 min read

Hello Everyone 😊

Today we are back with Express Router middleware.

But firstly a quick intro on Middleware function

Middleware functions are functions that have access to the request object (req), the response (res) object and the next (next) middleware function in the application’s request-response cycle

Middleware, as the name presume, hijack your request so that you can do anything that you want with the request or response eg: Validate Users, Modify the data or call the next middleware.

Middleware functions are just like your normal functions but with three parameters, i.e req, res and next.

If peradventure, the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

Say, we want to log the ‘method’ the user is using, the ‘url’ the user is trying to access and ‘a date’ in our different route (home and about route).

Let’s practice with code, shall we?

Consider an express app shown below :-

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

// req => middleware => res

const logger = (req, res, next) => {
  const method = req.method;
  const url = req.url;
  const time = new Date().getFullYear();
  console.log(`User requested a ${method} method using ${url} url on ${time}`)

  next();
};

app.get("/", (req, res) => {
  res.send("Home");
});

app.get("/about", (req, res) => {
  res.send("About");
});

app.listen(5000, () => {
  console.log("server running at 5000...");
});

The code above has our middleware function ‘logger’ BUT not yet accessed by the different route available. You should observe that the logger function is accessing the req method and getting informations its need and most importantly calling the ‘next()’ method, This is important as its calls the next middleware. If not called, your server will keep running.

After this understanding, what next ?

Now we pass the middleware function to express instance (app) method using app.use()

What’s app.use([path], callback) ?


This mount the specified middleware function(s) at the specified path, the middleware is executed when the base of the requested path matches path. BUT if you omit the path , it’s going to apply the callback (which is the middleware in our case) to all the route available. So, anytime a user access the home route(‘/’) and about route(‘/about’), the logger middleware showing their method, url and time is display on our console.

See code below :-

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

// req => middleware => res

const logger = (req, res, next) => {
  const method = req.method;
  const url = req.url;
  const time = new Date().getFullYear();
  console.log(`User requested a ${method} method using ${url} url on ${time}`)
  next();
};

app.use(logger) //without path, the logger middleware is going to match all route

app.get("/", (req, res) => {
  res.send("Home");
});

app.get("/about", (req, res) => {
  res.send("About");
});

app.listen(5000, () => {
  console.log("server running at 5000...");
});

Now on your browser if you go to localhost:5000/ and localhosst:500/about. On your terminal you should see the logger as :-

20210611_015707.png

Big Question ? What will happen if a path is specified in the app.use() method ?

The middleware function will only match the routes with the path base, right ?

Check the code out,

// the logger middleware won't be accessed on these routes
app.get("/", (req, res) => {
  res.send("Home");
});

app.get("/about", (req, res) => {
  res.send("About");
});

// the logger will only be accesed when these route hit as its starts from /api
app.get('/api/products', (req,res)=>{
  res.send('Product page')
});
app.get('/api/interns', (req,res)=>{
  res.send("Interns page");
});

From the code, app.use() has a path that matches ‘/api/’ so any routes that starts from that path only, will trigger the logger middleware hence localhost:5000/api/products and localhost:5000/api/interns.

So same concept, we can use a Router middleware to validate user, same concept. You can basically go crazy with the express router middleware.

Cover Credit: agileactors

Thanks for Reading!!! ✨ ✨ ⭐

Â