While Express ships built-ins and npm has middleware for almost everything, real applications always end up writing a few custom middleware functions of their own. This lesson walks through several practical examples.
Anatomy of a Custom Middleware Function
A custom middleware function is just a regular JavaScript function following the (req, res, next) signature. What makes it useful is what it does with req, res, or the flow of control before calling next().
The cleanest custom middleware functions do one thing, logging, auth, timing, and are named descriptively so their purpose is obvious wherever they are used.
Each function focuses on one concern: authentication, authorization, validation, then the actual business logic.
Common Mistakes
Writing middleware that does too many unrelated things instead of composing several focused functions.
Forgetting that a middleware factory must return a function, not run the logic immediately.
Mutating shared state instead of attaching data to the current req/res objects.
Not calling next() on every code path, including inside try/catch blocks.
Key Takeaways
Custom middleware is a plain (req, res, next) function you write for app-specific needs.
The middleware factory pattern lets you configure reusable middleware with arguments.
Compose several small middleware functions instead of one large handler.
Always call next() (or send a response) on every possible code path.
Pro Tip
Name custom middleware functions descriptively (requireAuth, logRequests, validateOrderBody) instead of anonymous arrow functions, stack traces and route definitions become far easier to read.
You now know how to write your own middleware. Next, learn how to organize routes into modular units with the Express Router lesson.