How to rely on other middlewares in express?

41 views Asked by At

What is the best practice for relying on other middlewares in an express middleware? Let's say my middleware relies on having bodyParser before it executes. Is there a better way than telling my users explicitly in the readme to include and run my dependencies first?

1

There are 1 answers

0
robertklep On BEST ANSWER

If your middleware requires body-parser and it would insert that middleware into the middleware chain itself, it may become problematic when the user is already including body-parser in their app (in other words, body-parser would be included twice).

It may work (never tried), but it may also cause unintended side effects, which is why I would document the requirement for body-parser but have the user install it themselves. Your middleware can explicitly throw an exception when it sees that req.body isn't defined for a request.