Node.js Architecture

Good Node architecture is simple, boring, and explicit. Keep boundaries small, isolate I/O, and keep the runtime entrypoint thin.

Common use cases

Node.js fits workloads where non-blocking I/O, fast JSON handling, and shared JavaScript/TypeScript tooling deliver high productivity:

  • HTTP APIs and backend services: REST/GraphQL gateways, BFFs (Backend-for-Frontend), and webhook processors.
  • CLI tools and automation scripts: Repository linters, code generators, and deployment helpers.
  • Build tooling and dev servers: Bundlers, static-site generators, and local mock servers.
  • Real-time apps: WebSocket servers, chat relays, and Server-Sent Events (SSE) streams.

Layered layout

Organizing files by responsibility prevents HTTP request objects (req, res) and SQL queries from leaking into core business logic:

src/
  app.ts          # process bootstrap and composition root
  routes/         # HTTP or CLI adapters
  services/       # business rules
  data/           # persistence and external I/O
  config/         # environment and startup settings
  types/          # shared domain types

Design rules

Apply these four boundary rules so services stay testable as they grow:

  1. Keep the entry file small and startup-only (load config, wire dependencies, start listening, handle SIGTERM).
  2. Separate business rules from transport code so services can be tested without HTTP mocks.
  3. Wrap external APIs and databases in repository/client adapters so you can swap providers or inject fakes in tests.
  4. Validate environment variables once at startup and fail fast if required secrets are missing.

Architecture choice

For most Node apps, start with a layered or feature-based architecture. Use a feature-based structure (grouping users/, billing/, orders/ with their own routes and services) when the app grows by product area. Use a layered structure when the app is small, service-oriented, or needs a clean separation between HTTP, services, and persistence.

Practice

Map out a clean boundary between transport and domain logic:

  1. Sketch a Node app with an entry file, one service, and one adapter.
  2. Mark which file is allowed to touch HTTP and which file contains business rules.
  3. Write one trade-off note about layered versus feature-based structure.