INTRO
Express is minimal on purpose. Without conventions, every developer adds another `try/catch` variant. I treat middleware as a pipeline: parse → authenticate → authorize → validate → handler → error formatter.
Order of operations
`express.json()` and urlencoded parsers first. Then request id, logger, cors (if needed), rate limit on public routes, then auth.
Route-specific middleware comes last before the handler. Global auth on `/api` is fine; do not run heavy DB lookups on health checks.
Validation as middleware
Zod or Joi schemas validate `body`, `query`, and `params` before handlers run. Handlers assume types are sane - less branching, fewer 500s from `undefined` access.
Return 422 with field errors for validation; reserve 400 for malformed JSON.
code-snippet.typescript
const validate = (schema: ZodSchema) => (req, res, next) => {
const parsed = schema.safeParse({
body: req.body,
query: req.query,
params: req.params,
})
if (!parsed.success) {
return res.status(422).json({ code: 'VALIDATION_ERROR', details: parsed.error.flatten() })
}
req.validated = parsed.data
next()
}Central error handler
Throw or `next(err)` with typed errors (`OperationalError` vs unknown). The last middleware maps known errors to status codes and logs unknowns with stack traces.
Never leak stack traces to clients in production.
KEY TAKEAWAYS
“Fix middleware order once; document it for the team.”
- 02
Validate inputs at the edge; keep handlers thin.
- 03
Use one error formatter; distinguish operational vs programmer bugs.
CONCLUSION
Closing thought
Express scales with discipline: predictable pipelines beat clever one-off routes. Middleware is how you encode that discipline. Ready to talk scope? Use Contact — or browse Services for fit.
CONTINUE
Related pages
UP NEXT
SEO-Friendly Next.js Business Websites (Without Killing UX)
How to build SEO-friendly Next.js business sites that stay fast: page intent, App Router metadata, LCP/CLS, and lean client JavaScript — without keyword stuffing.
Read next article