Facebook Pixel

When should I write custom middleware vs put logic in a handler?

Write middleware for cross-cutting concerns (auth, validation, logging, request IDs, permissions). Put business logic in handlers or services. Middleware shapes the request; logic acts on it.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in How to Write Custom Middleware in Express

Use the (req, res, next) signature. Do something with req or res, then call next() to continue or send a response to end the cycle. Keep middlewares small and one-job.

Use a factory function. The factory takes options and returns a middleware. Example: validate(schema) returns a middleware that validates against that schema. requireRole(role) returns a middleware that checks that role.

Express 4 does not catch promise rejections from async middlewares. Wrap with Promise.resolve(fn(req, res, next)).catch(next) so rejections go to the error handler instead of being swallowed.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.