Why Middleware Should Only Be a Gatekeeper, Not a Business Logic Handler
A software development article on DEV Community warns against overloading HTTP middleware with business logic, using a subscription-verification example that grew from 3 lines to 80. The bloated middleware deducts credits, updates database fields, and sends expiry emails — tasks that only execute on HTTP requests, silently skipping console commands, queued jobs, or ungrouped API routes. The article also highlights that credits are deducted before the controller runs, meaning a failed request still results in a charge. It further notes that redirecting API clients to an HTML page causes confusing errors on mobile and frontend apps, while inline email dispatch can slow every request if the mail server is unresponsive. The author recommends keeping middleware strictly to access control, rate limiting, and request/response adjustments, while moving all business rules into dedicated service classes.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in