Engineering Insights

Building Scalable REST APIs with Node.js, Express, and TypeScript

Designing Clean Node.js Service Architectures

Building maintainable backend systems requires decoupling HTTP route controllers from business logic and database access layers. A structured layered approach prevents bloated files and simplifies automated testing.

1. Layered Architecture Pattern

  • Controllers: Parse HTTP requests, validate request parameters, and return formatted JSON responses.
  • Services: Contain domain business logic, transactional decisions, and third-party API orchestrations.
  • Repositories / ORM Models: Handle direct database queries (Firestore, PostgreSQL, Prisma, Drizzle).

2. Centralized Error Handling

Avoid scattering try/catch blocks across every route by leveraging an async wrapper pattern or middleware error handler in Express:

export class AppError extends Error {
  constructor(public statusCode: number, message: string) {
    super(message);
    Object.setPrototypeOf(this, AppError.prototype);
  }
}

export const errorHandler = (err: any, req: Request, res: Response, next: NextFunction) => {
  const status = err.statusCode || 500;
  const message = err.message || 'Internal Server Error';
  res.status(status).json({ success: false, error: message });
};

3. Essential Production Middlewares

  • Helmet: Sets HTTP security headers (CSP, HSTS, X-Frame-Options).
  • Express Rate Limit: Prevents brute-force attacks and DDoS by bounding request frequencies per IP.
  • Cors: Restricts API invocation strictly to verified client origins.