๐๐๐ถ๐น๐ฑ๐ถ๐ป๐ด ๐ ๐ฃ๐ฟ๐ผ๐ฑ๐๐ฐ๐๐ถ๐ผ๐ป ๐ฅ๐ฒ๐ฎ๐ฑ๐ ๐๐ฎ๐ฐ๐ธ๐ฒ๐ป๐ฑ
You need data integrity for a finance app. One bug will crash your server. Weak types will corrupt your database.
I built a backend using Express, TypeScript, and Zod. Here is how to make it stable.
Stop writing try/catch in every controller. It clutters your code. Use a wrapper function. It catches errors and sends them to a global handler.
Avoid using "any" for request objects. It kills type safety. Use declaration merging. This adds user IDs and request IDs to the Express Request object.
Keep validation out of your logic. Use a middleware factory with Zod. It checks data before your controller sees it. This keeps your routes clean.
One global error middleware handles everything. It catches Zod errors and custom app errors. You stop writing repetitive response strings.
Middleware order is key.
- Request tracing runs first.
- Security and limits come next.
- Performance tools run third.
- Routes come fourth.
- The error handler runs last.
This architecture gives you three wins.
- No unhandled crashes.
- Full type safety for requests.
- Cleaner code for reviews.
How do you structure your Express apps? Do you use declaration merging or a different pattern?