Design the structure of Node.js/TypeScript back-end systems — modular monolith versus separate services, feature modules and ports-and-adapters, NestJS modules versus Fastify plugins, dependency injection and the composition root, data ownership, multi-tenancy, where authentication and caching sit, containers versus serverless, monorepos with pnpm workspaces, Turborepo or Nx, and the ADR that records it.
When agents use itUse this whenever the user structures a new Node service, asks where code should live, splits or merges services, sets up pnpm-workspace.yaml, turbo.json, nx.json or package.json workspaces, edits app.module.ts or nest-cli.json, asks "microservices or monolith", "containers or serverless", where the Stripe client or the auth check belongs, or how two teams should share code without coupling. Also use it when a Node system needs an architecture decision record.
Install
Copilot (VS Code, Visual Studio, Copilot CLI and github.com) reads skills from the repository — commit them so the whole team gets them.
npx skills add AGCO-Global/org-skills --skill nodejs-architecture -a github-copilot
# or with the org installer (adds .github/skills/nodejs-architecture):
npx -y github:AGCO-Global/org-skills add skill nodejs-architecture
Uses the open skills CLI. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, OpenCode, Windsurf and 60+ others — it asks which agent to install into.
Installs the backend-nodejs-skills plugin, which bundles all Backend / Node.js skills and keeps them updated.
/plugin marketplace add AGCO-Global/org-skills
/plugin install backend-nodejs-skills@org-skills
# or just this skill, in this repository:
npx skills add AGCO-Global/org-skills --skill nodejs-architecture -a claude-code
Use Download .zip above, then upload it under Customize → Skills → Upload skill. Team and Enterprise admins can sync this repo as a plugin marketplace instead.
Installs into .agents/skills/, which Codex reads.
npx skills add AGCO-Global/org-skills --skill nodejs-architecture -a codex
Installs into Cursor's skills folder.
npx skills add AGCO-Global/org-skills --skill nodejs-architecture -a cursor
Installs into Gemini CLI's skills folder.
npx skills add AGCO-Global/org-skills --skill nodejs-architecture -a gemini-cli
Nothing to install. Press Download .zip above, unzip it, and drop the nodejs-architecture folder into your tool's skills folder — .claude/skills/, .github/skills/, .cursor/skills/ or .agents/skills/. Step-by-step, per tool: How to use it. For any other tool with rules or custom prompts, Copy SKILL.md and paste it in — it is plain Markdown.
The npx commands need Node.js 20+ and use your normal git sign-in to GitHub, so they work while the repository is private. Without Node.js, see the No Node.js tab — a skill is a folder of Markdown, so copying it in works just as well.
Start as a well-bounded modular monolith and earn every network hop. Node back-ends fail from tangled modules and hidden coupling far more often than from a lack of microservices, so the architecture's job is to keep the domain testable without HTTP, the database or the broker — and to make every boundary something CI can check.
1. Decide first
Question
Default
Change when
One deployable or many?
Modular monolith: one process, feature modules with enforced boundaries
A module needs independent scaling, its own release cadence or a different runtime
Splitting by team
Services per bounded context, integrated asynchronously
Two teams share a schema — fix data ownership before splitting, or you get a distributed monolith
Internal structure
Feature modules with a lite ports-and-adapters split
Small service with one adapter → the flat layout in nodejs-development §2; add ports when a second adapter or a hard-to-run dependency appears
Framework structure
Fastify plugins, one per feature
Large codebase, many teams → NestJS 12 modules; smallest magic → a manual composition root
CPU-heavy work
A separate queue-fed worker service
Never in the API process — it blocks the event loop for every request
Hosting
Container
Bursty, event-triggered, low steady traffic → serverless, accepting cold starts, per-invocation limits and a database pooler
Token validation
At each service, against the IdP's JWKS
Many internal services behind one entry point → validate at the gateway and forward an internal token
Cache placement
Inside the module that owns the data
Never a cache shared between modules; that restores the coupling you removed
A service owns its data. Two services writing the same tables are one service with extra latency.
2. Inside a service
src/
modules/orders/
domain/ entity, value objects, domain errors, pure rules — no I/O imports
application/ use cases: placeOrder, cancelOrder — depend on ports
ports.ts OrderRepository, PaymentGateway, EventPublisher interfaces
adapters/ http routes, Prisma repository, payment client, message consumer
index.ts the module's public API — other modules import only this
platform/ config, logger, db, telemetry, error mapping
app.ts composition root: wires adapters to use cases, registers routes
Transport (HTTP route, queue consumer, cron, CLI) is a thin adapter: parse, call one use case, map the result. The same use case then serves a REST route and a Kafka consumer without duplication.
Domain code never imports fastify, @nestjs/*, an ORM client or process.env.
Keep it lite. A port earns its place when a second implementation exists or a test needs to replace something expensive (database, external API, clock, id generator). Wrapping every function in an interface is ceremony, and it is why teams abandon this layout.
A small service does not need this shape at all. Start with nodejs-development's flat module layout and grow into this one when the second adapter arrives; say which you are using in the ADR so the two conventions do not appear in the same repository by accident.
3. Make the boundaries enforceable
A rule nobody checks is a rule that decays in a sprint. Pick one tool and fail CI on it:
// .dependency-cruiser.cjs
module.exports = {
forbidden: [
{
name: 'no-cross-module-internals',
comment: 'Modules talk through index.ts, never into each other\'s folders',
severity: 'error',
from: { path: '^src/modules/([^/]+)/.+' },
to: { path: '^src/modules/([^/]+)/.+', pathNot: '^src/modules/$1/.+|^src/modules/[^/]+/index\\.ts$' },
},
{
name: 'domain-is-pure',
comment: 'Domain must not know about transport or persistence',
severity: 'error',
from: { path: '^src/modules/[^/]+/domain/.+' },
to: { path: 'node_modules/(fastify|express|@nestjs|@prisma|drizzle-orm)' },
},
],
options: { tsConfig: { fileName: './tsconfig.json' }, doNotFollow: { path: 'node_modules' } },
};
eslint-plugin-boundaries and Nx tag constraints express the same rules; full configurations and the CI wiring are in references/boundary-rules.md.
4. Framework structure and dependency injection
Option
Fits
Notes
Fastify plugins
Lean services
One encapsulated plugin per feature; share infrastructure by decorating through fastify-plugin; features never reach into another's decorators
NestJS 12 modules
Large codebases, teams used to Angular or Spring patterns
Core packages ship as ESM and need Node ≥ 20.19/22.12; nest new asks CommonJS or ESM (ESM gets Vitest). Migrating a CommonJS Nest 11 app is a project — plan it. forwardRef is a cycle asking to be broken with an event
Manual composition root
Any framework; the least magic
Plain constructor or factory injection in app.ts; the easiest to read and to test
awilix / tsyringe
Many dependencies without Nest
Prefer awilix (no decorators). Never resolve from the container inside domain code
Pass dependencies explicitly. A module-level singleton imported everywhere (import { db } from '../db') is invisible coupling: it cannot be replaced in a test and it makes per-tenant wiring impossible.
5. Contracts and integration
Both are owned elsewhere in this catalog. An ADR should link, not restate.
HTTP contracts — resources, status codes, pagination, idempotency, versioning and deprecation: api-design. The Node-specific choice is the style: REST + OpenAPI for public and partner APIs; GraphQL (Mercurius, Yoga, Apollo) only with DataLoader, depth and complexity limits and persisted queries; tRPC only inside one monorepo with TypeScript on both ends; gRPC or Connect for service-to-service and cross-language contracts — plain gRPC needs a proxy for browsers, while the Connect protocol serves browsers directly.
Asynchronous integration — outbox, idempotent consumers, event versioning, retries, DLQ, sagas: messaging-patterns. The Node-specific choice is the transport: BullMQ (Redis) for job distribution, pg-boss or Graphile Worker when you would rather not add Redis and can relay the outbox from the same Postgres, Kafka or Kinesis when several consumer groups need the same events or replay matters.
6. Multi-tenancy, migrations and configuration
Resolve the tenant once at the edge from the validated token (never a header the caller controls), carry it in AsyncLocalStorage, and make it impossible to query without it — row-level security, or a repository layer that takes the tenant as a required argument. Isolation models: shared tables with tenant_id (cheapest), schema per tenant (migration fan-out), database per tenant (strongest, most operations).
Each module owns its tables and its migrations; migrations ship with the module and are applied by the pipeline, not at boot by every instance (database-migrations). If module B's migration must run before module A's, they share a table and the boundary is wrong.
Configuration is validated once at boot and injected (nodejs-development §5). Use feature flags rather than branching on the environment name — an environment-name if in business code is a deployment you cannot test.
A BFF is justified when a client genuinely needs a different shape (mobile payload trimming, browser session cookies). A BFF that forwards one-to-one is a hop that costs latency and buys nothing.
7. Monorepos and shared packages
pnpm workspaces as the base; Turborepo for task caching with minimal opinion; Nx when you want generators, an affected graph in CI and enforced module boundaries. Layout: apps/<service>, packages/<lib>, packages/tsconfig, packages/eslint-config, internal dependencies as workspace:*.
Share contracts — schemas, event types, generated clients — and platform utilities. Do not share domain entities between services: that is the coupling you split them to avoid, and it means one team's refactor breaks another's deploy. Build and ship only affected apps, each from a pruned workspace. Details: references/monorepo-and-packages.md.
8. Deliverable format
# ADR-NNN: <decision>
Status: Proposed | Accepted Date: <yyyy-mm-dd>
## Context forces, constraints, team size, load, SLAs
## Options 2–4 options with their trade-offs
## Decision the choice, and the one condition that would flip it
## Consequences what gets easier, what gets harder, the migration steps
## Guardrails the lint rule, boundary config or CI check that enforces it
## Structure module map, folder tree, sequence of messages
Checklist
The decision names the condition that would reverse it.
Every boundary has a lint or CI rule, not just a convention.
The internal layout (flat or ports-and-adapters) is stated and used consistently.
Each module owns its tables and its migrations; no cross-module writes.
Domain code imports no framework, ORM or process.env.
Tenant resolution comes from the validated token and cannot be bypassed.
HTTP contract rules defer to api-design; async integration defers to messaging-patterns.
Hosting choice follows the workload shape; serverless names its pooler and cold-start budget.
Shared packages contain contracts and utilities, never domain entities.
Anti-patterns
Microservices from day one for one team → modular monolith, extract on a named force.
Services sharing a database → a distributed monolith; fix ownership first.
Domain logic in route handlers or ORM entities → use case in application/, entity in domain/.
Cross-module deep imports → import the module's index.ts; enforce it (§3).
A utils/ package every module depends on → move code to its owner, or a small named package.
forwardRef to break a cycle → the cycle is the design; invert it or use an event.
import { db } from '../db' in a use case → inject it through the composition root.
Tenant filtering left to each query author's memory → row-level security or a repository that requires the tenant.
Shared package of domain entities → contracts only: schemas and DTOs.
One health endpoint for liveness and readiness → two, with different meanings (service-operability).
Go deeper
references/boundary-rules.md — complete dependency-cruiser and eslint-plugin-boundaries configurations, Nx tag constraints, and how to fail CI on a violation without blocking legitimate refactors.
Sibling skills: nodejs-development for the code, nodejs-testing for tests, nodejs-performance for symptoms, api-design, messaging-patterns, database-migrations, service-operability, backend-code-review for reviews.
---
name: nodejs-architecture
description: >
Design the structure of Node.js/TypeScript back-end systems — modular monolith versus separate services, feature modules and ports-and-adapters, NestJS modules versus Fastify plugins, dependency injection and the composition root, data ownership, multi-tenancy, where authentication and caching sit, containers versus serverless, monorepos with pnpm workspaces, Turborepo or Nx, and the ADR that records it. Use this whenever the user structures a new Node service, asks where code should live, splits or merges services, sets up pnpm-workspace.yaml, turbo.json, nx.json or package.json workspaces, edits app.module.ts or nest-cli.json, asks "microservices or monolith", "containers or serverless", where the Stripe client or the auth check belongs, or how two teams should share code without coupling. Also use it when a Node system needs an architecture decision record.
metadata:
technology: Node.js
type: architecture
---
# Node.js Architecture
> **Targets:** Node 24 LTS, TypeScript 6, ESM, NestJS 12, Fastify 5, pnpm workspaces · **Verified:** 2026-09 against https://docs.nestjs.com/migration-guide and https://nodejs.org/en/about/previous-releases
Start as a well-bounded modular monolith and earn every network hop. Node back-ends fail from tangled modules and hidden coupling far more often than from a lack of microservices, so the architecture's job is to keep the domain testable without HTTP, the database or the broker — and to make every boundary something CI can check.
## 1. Decide first
| Question | Default | Change when |
|---|---|---|
| One deployable or many? | **Modular monolith**: one process, feature modules with enforced boundaries | A module needs independent scaling, its own release cadence or a different runtime |
| Splitting by team | Services per bounded context, integrated asynchronously | Two teams share a schema — fix data ownership *before* splitting, or you get a distributed monolith |
| Internal structure | Feature modules with a **lite** ports-and-adapters split | Small service with one adapter → the flat layout in `nodejs-development` §2; add ports when a second adapter or a hard-to-run dependency appears |
| Framework structure | Fastify plugins, one per feature | Large codebase, many teams → NestJS 12 modules; smallest magic → a manual composition root |
| CPU-heavy work | A separate queue-fed worker service | Never in the API process — it blocks the event loop for every request |
| Hosting | Container | Bursty, event-triggered, low steady traffic → serverless, accepting cold starts, per-invocation limits and a database pooler |
| Token validation | At each service, against the IdP's JWKS | Many internal services behind one entry point → validate at the gateway and forward an internal token |
| Cache placement | Inside the module that owns the data | Never a cache shared between modules; that restores the coupling you removed |
A service owns its data. Two services writing the same tables are one service with extra latency.
## 2. Inside a service
```
src/
modules/orders/
domain/ entity, value objects, domain errors, pure rules — no I/O imports
application/ use cases: placeOrder, cancelOrder — depend on ports
ports.ts OrderRepository, PaymentGateway, EventPublisher interfaces
adapters/ http routes, Prisma repository, payment client, message consumer
index.ts the module's public API — other modules import only this
platform/ config, logger, db, telemetry, error mapping
app.ts composition root: wires adapters to use cases, registers routes
```
- Transport (HTTP route, queue consumer, cron, CLI) is a thin adapter: parse, call one use case, map the result. The same use case then serves a REST route and a Kafka consumer without duplication.
- Domain code never imports `fastify`, `@nestjs/*`, an ORM client or `process.env`.
- Keep it **lite**. A port earns its place when a second implementation exists or a test needs to replace something expensive (database, external API, clock, id generator). Wrapping every function in an interface is ceremony, and it is why teams abandon this layout.
- A small service does not need this shape at all. Start with `nodejs-development`'s flat module layout and grow into this one when the second adapter arrives; say which you are using in the ADR so the two conventions do not appear in the same repository by accident.
## 3. Make the boundaries enforceable
A rule nobody checks is a rule that decays in a sprint. Pick one tool and fail CI on it:
```js
// .dependency-cruiser.cjs
module.exports = {
forbidden: [
{
name: 'no-cross-module-internals',
comment: 'Modules talk through index.ts, never into each other\'s folders',
severity: 'error',
from: { path: '^src/modules/([^/]+)/.+' },
to: { path: '^src/modules/([^/]+)/.+', pathNot: '^src/modules/$1/.+|^src/modules/[^/]+/index\\.ts$' },
},
{
name: 'domain-is-pure',
comment: 'Domain must not know about transport or persistence',
severity: 'error',
from: { path: '^src/modules/[^/]+/domain/.+' },
to: { path: 'node_modules/(fastify|express|@nestjs|@prisma|drizzle-orm)' },
},
],
options: { tsConfig: { fileName: './tsconfig.json' }, doNotFollow: { path: 'node_modules' } },
};
```
`eslint-plugin-boundaries` and Nx tag constraints express the same rules; full configurations and the CI wiring are in `references/boundary-rules.md`.
## 4. Framework structure and dependency injection
| Option | Fits | Notes |
|---|---|---|
| **Fastify plugins** | Lean services | One encapsulated plugin per feature; share infrastructure by decorating through `fastify-plugin`; features never reach into another's decorators |
| **NestJS 12 modules** | Large codebases, teams used to Angular or Spring patterns | Core packages ship as ESM and need Node ≥ 20.19/22.12; `nest new` asks CommonJS or ESM (ESM gets Vitest). Migrating a CommonJS Nest 11 app is a project — plan it. `forwardRef` is a cycle asking to be broken with an event |
| **Manual composition root** | Any framework; the least magic | Plain constructor or factory injection in `app.ts`; the easiest to read and to test |
| **awilix / tsyringe** | Many dependencies without Nest | Prefer awilix (no decorators). Never resolve from the container inside domain code |
Pass dependencies explicitly. A module-level singleton imported everywhere (`import { db } from '../db'`) is invisible coupling: it cannot be replaced in a test and it makes per-tenant wiring impossible.
## 5. Contracts and integration
Both are owned elsewhere in this catalog. An ADR should link, not restate.
- **HTTP contracts** — resources, status codes, pagination, idempotency, versioning and deprecation: `api-design`. The Node-specific choice is the style: **REST + OpenAPI** for public and partner APIs; **GraphQL** (Mercurius, Yoga, Apollo) only with DataLoader, depth and complexity limits and persisted queries; **tRPC** only inside one monorepo with TypeScript on both ends; **gRPC or Connect** for service-to-service and cross-language contracts — plain gRPC needs a proxy for browsers, while the Connect protocol serves browsers directly.
- **Asynchronous integration** — outbox, idempotent consumers, event versioning, retries, DLQ, sagas: `messaging-patterns`. The Node-specific choice is the transport: **BullMQ** (Redis) for job distribution, **pg-boss** or **Graphile Worker** when you would rather not add Redis and can relay the outbox from the same Postgres, **Kafka or Kinesis** when several consumer groups need the same events or replay matters.
## 6. Multi-tenancy, migrations and configuration
- Resolve the tenant once at the edge from the **validated token** (never a header the caller controls), carry it in `AsyncLocalStorage`, and make it impossible to query without it — row-level security, or a repository layer that takes the tenant as a required argument. Isolation models: shared tables with `tenant_id` (cheapest), schema per tenant (migration fan-out), database per tenant (strongest, most operations).
- Each module owns its tables and its migrations; migrations ship with the module and are applied by the pipeline, not at boot by every instance (`database-migrations`). If module B's migration must run before module A's, they share a table and the boundary is wrong.
- Configuration is validated once at boot and injected (`nodejs-development` §5). Use feature flags rather than branching on the environment name — an environment-name `if` in business code is a deployment you cannot test.
- A BFF is justified when a client genuinely needs a different shape (mobile payload trimming, browser session cookies). A BFF that forwards one-to-one is a hop that costs latency and buys nothing.
## 7. Monorepos and shared packages
**pnpm workspaces** as the base; **Turborepo** for task caching with minimal opinion; **Nx** when you want generators, an affected graph in CI and enforced module boundaries. Layout: `apps/<service>`, `packages/<lib>`, `packages/tsconfig`, `packages/eslint-config`, internal dependencies as `workspace:*`.
Share **contracts** — schemas, event types, generated clients — and platform utilities. Do **not** share domain entities between services: that is the coupling you split them to avoid, and it means one team's refactor breaks another's deploy. Build and ship only affected apps, each from a pruned workspace. Details: `references/monorepo-and-packages.md`.
## 8. Deliverable format
```
# ADR-NNN: <decision>
Status: Proposed | Accepted Date: <yyyy-mm-dd>
## Context forces, constraints, team size, load, SLAs
## Options 2–4 options with their trade-offs
## Decision the choice, and the one condition that would flip it
## Consequences what gets easier, what gets harder, the migration steps
## Guardrails the lint rule, boundary config or CI check that enforces it
## Structure module map, folder tree, sequence of messages
```
## Checklist
- [ ] The decision names the condition that would reverse it.
- [ ] Every boundary has a lint or CI rule, not just a convention.
- [ ] The internal layout (flat or ports-and-adapters) is stated and used consistently.
- [ ] Each module owns its tables and its migrations; no cross-module writes.
- [ ] Domain code imports no framework, ORM or `process.env`.
- [ ] Tenant resolution comes from the validated token and cannot be bypassed.
- [ ] HTTP contract rules defer to `api-design`; async integration defers to `messaging-patterns`.
- [ ] Hosting choice follows the workload shape; serverless names its pooler and cold-start budget.
- [ ] Shared packages contain contracts and utilities, never domain entities.
## Anti-patterns
- **Microservices from day one for one team** → modular monolith, extract on a named force.
- **Services sharing a database** → a distributed monolith; fix ownership first.
- **Domain logic in route handlers or ORM entities** → use case in `application/`, entity in `domain/`.
- **Cross-module deep imports** → import the module's `index.ts`; enforce it (§3).
- **A `utils/` package every module depends on** → move code to its owner, or a small named package.
- **`forwardRef` to break a cycle** → the cycle is the design; invert it or use an event.
- **`import { db } from '../db'` in a use case** → inject it through the composition root.
- **Tenant filtering left to each query author's memory** → row-level security or a repository that requires the tenant.
- **Shared package of domain entities** → contracts only: schemas and DTOs.
- **One health endpoint for liveness and readiness** → two, with different meanings (`service-operability`).
## Go deeper
- `references/boundary-rules.md` — complete `dependency-cruiser` and `eslint-plugin-boundaries` configurations, Nx tag constraints, and how to fail CI on a violation without blocking legitimate refactors.
- `references/monorepo-and-packages.md` — pnpm workspace layout, TypeScript project references, Turborepo versus Nx, `turbo prune` and `pnpm deploy` Docker builds, versioning internal packages.
- Sibling skills: `nodejs-development` for the code, `nodejs-testing` for tests, `nodejs-performance` for symptoms, `api-design`, `messaging-patterns`, `database-migrations`, `service-operability`, `backend-code-review` for reviews.