Route Middleware with Code Examples

What is Route Middleware?

  1. Middleware applied to specific routes only
  2. Executes before the final route handler


How to Make Route Middleware

function checkAgeRouteMiddleware(req, resp, next) {
console.log(req.query);

if (!req.query.age || req.query.age < 18) {
resp.send("Yoru are not allowed to use this website");
} else {
next();
}
}


function checkUrl(req, resp, next) {
console.log("this req url is " + req.url);
next();
}


How to Apply Route Middleware

  1. Use middleware as a second parameter
  2. You can apply multiple middleware functions on a single route



app.get("/", (req, resp) => {
resp.send("<h1>Home page</h1>");
});

app.get("/login", checkUrl, (req, resp) => {
resp.send("<h1>login page</h1>");
});

app.get("/users", checkAgeRouteMiddleware, checkUrl, (req, resp) => {
resp.send("<h1>users page</h1>");
});

app.get("/products", checkAgeRouteMiddleware, checkUrl, (req, resp) => {
resp.send("<h1>products page</h1>");
});