Categories
JavaScript Answers

How to create a Express.js middleware that accepts parameters with JavaScript?

Spread the love

To create a Express.js middleware that accepts parameters with JavaScript, we return a function that takes the arguments we want.

For instance, we write

const hasRole = (role) => {
  return (req, res, next) => {
    if (role !== req.user.role) {
      res.redirect("...");
    } else {
      next();
    }
  };
};

const middlwareHasRoleAdmin = hasRole("admin");

app.get("/hasToBeAdmin", middlwareHasRoleAdmin, (req, res) => {});

to define the hasRole function.

It returns a middleware function that checks the role and either redirects with res.redirect or move to the next middleware with next.

Then we call hasRole with 'admin' to return a middleware with role set to 'admin'.

And we use the middlwareHasRoleAdmin middleware in our /hasToBeAdmin route.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *