Build production-grade Node.js back-end services in TypeScript — framework choice (Fastify, NestJS, Express, Hono), ESM and strict tsconfig, schema validation at the edge with Zod 4 or TypeBox, typed domain errors mapped to problem+json, a validated config module, data access with Prisma 7, Drizzle or Kysely, outbound HTTP with timeouts and idempotency, auth, pino logging and background jobs.
When agents use itUse this whenever the user asks to write, scaffold, refactor or debug a Node/TypeScript API, route, controller, plugin, middleware or worker; edits package.json, tsconfig.json, app.ts, server.ts, main.ts, app.module.ts, prisma.config.ts or .env; asks about Zod, TypeBox, Prisma, Drizzle, Kysely, JWT, sessions, BullMQ, helmet, rate limiting or OpenAPI generation; or hits "unhandled promise rejection", "ERR_REQUIRE_ESM" or "how do I do X in Fastify/NestJS/Express". Also use it when porting a service from CommonJS to ESM. For tests use nodejs-testing; for latency or memory symptoms use nodejs-performance.
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-development -a github-copilot
# or with the org installer (adds .github/skills/nodejs-development):
npx -y github:AGCO-Global/org-skills add skill nodejs-development
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-development -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-development -a codex
Installs into Cursor's skills folder.
npx skills add AGCO-Global/org-skills --skill nodejs-development -a cursor
Installs into Gemini CLI's skills folder.
npx skills add AGCO-Global/org-skills --skill nodejs-development -a gemini-cli
Nothing to install. Press Download .zip above, unzip it, and drop the nodejs-development 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.
A Node service is one process multiplexing thousands of requests on one thread: anything that blocks, leaks, throws unhandled or trusts its input hurts every request at once. Write each handler assuming hostile input, a slow dependency and a SIGTERM arriving mid-request. Check the project's pins first — engines, .nvmrc, the Dockerfile base image, and the majors in package.json — because most of the advice below changed in a recent major.
1. Decide first
Question
Default
Change when
Framework
Fastify 5 — schema-first validation, fast serialisation, plugin encapsulation
Many modules and a large team → NestJS 12; existing Express codebase → Express 5; edge or multi-runtime → Hono
Modules
ESM ("type": "module", module: "NodeNext")
An existing CommonJS codebase: require(esm) (Node 20.19+/22.12+) lets it consume ESM dependencies during a gradual migration
Runtime version
Active LTS — Node 24 (22 also LTS; 20 went EOL in March 2026)
The project pins otherwise; NestJS 12 needs ≥ 20.19 or 22.12 to run and a newer Node for its generators
Validation
Zod 4 (or TypeBox with Fastify's type provider)
NestJS: class-validator with ValidationPipe, or StandardSchemaValidationPipe to use Zod/Valibot
Error shape
RFC 9457 application/problem+json from one central handler
Never per-route ad-hoc JSON
Data access
Prisma 7 for productivity, Drizzle/Kysely when you want SQL shape and types
Serverless or edge → a driver adapter plus a pooler
Background work
A separate worker process (BullMQ, pg-boss, Graphile Worker)
Never "fire and forget" after the response in the request process
Where does business logic live?
A service module the route calls
It needs a second adapter (queue consumer, CLI) → ports and adapters (nodejs-architecture)
ESM for everything new, including NestJS 12 — its core packages ship as ESM, and nest new asks which you want (ESM projects get Vitest, CommonJS projects get Jest). Under NodeNext, relative imports carry the .js extension. Do not mix both module systems in one package.
erasableSyntaxOnly bans the TypeScript syntax Node's built-in type stripping cannot remove (enum, parameter properties, namespaces), so node --experimental-strip-types and tsx keep working. It turns a runtime surprise into a compile error.
Dev loop with tsx or Node's type stripping; production runs compiled JS from dist/. tsc --noEmit in CI either way.
Layout: src/modules/<feature>/{routes,service,repository,schemas}.ts, plus src/config.ts, src/app.ts (builds the app, never listens) and src/server.ts (listens, handles signals). Splitting app from server is what makes in-process HTTP tests possible.
3. Validate at the edge, trust inside
Every body, query, param and header you read is parsed by a schema, and the TypeScript type is inferred from that schema — never a hand-written parallel interface that can drift.
import { z } from 'zod';
const CreateOrder = z.object({
sku: z.string().min(1),
qty: z.number().int().positive().max(100),
notifyUrl: z.url().optional(), // Zod 4: top-level format, not z.string().url()
});
type CreateOrder = z.infer<typeof CreateOrder>;
Zod 4 moved string formats to top level (z.url(), z.email(), z.uuid()); the chained forms still work but are legacy. Error customisation is now one error option: z.string().min(5, { error: 'Too short.' }).
Validate responses too. Fastify response schemas also strip unlisted fields, which is what stops a passwordHash reaching a client by accident.
4. Errors: operational versus programmer
Operational (bad input, not found, conflict, dependency timeout): throw typed domain errors carrying a code; one central handler maps them to a status and a stable application/problem+json body. Never leak a stack trace, SQL or a driver message to a client.
Programmer errors (TypeError, broken invariant): log with full context, return 500, fix the bug. Do not map them to a friendly 400.
Async errors must reach the handler: Fastify and Express 5 forward rejected promises; Express 4 does not. Always await or return promises — turn on @typescript-eslint/no-floating-promises.
Central handler: Fastify setErrorHandler, an Express 5 four-argument middleware registered last, NestJS exception filters.
At process level, log fatally on uncaughtException and unhandledRejection and exit non-zero. Continuing runs the service in an unknown state; let the orchestrator restart it.
5. Config and secrets
// src/config.ts — the only file that reads process.env
import { z } from 'zod';
const Env = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']),
PORT: z.coerce.number().default(3000),
DATABASE_URL: z.url(),
JWT_ISSUER: z.url(),
});
export const config = Env.parse(process.env); // fails at boot with a readable message
Inject config or slices of it. process.env.X scattered through modules is unvalidated and untestable. .env is for local development only (node --env-file=.env), git-ignored, with a committed .env.example; deployed secrets come from the platform's secret store. Note that Prisma 7 no longer loads .env automatically — load it explicitly in prisma.config.ts.
6. Data access
Tool
Choose when
Watch
Prisma 7
Schema-first migrations, typed client, speed of delivery
v7 requires a driver adapter per database, is ESM-only, needs output in the generator block and a prisma.config.ts (references/data-and-http.md)
Drizzle
You want the SQL shape visible and types inferred
Younger ecosystem; you design more yourself
Kysely / Knex
Full SQL control, Kysely for types
You own mapping and migration discipline
TypeORM / MikroORM
The team wants entity and unit-of-work patterns (often with NestJS)
Lazy loading and N+1; read the generated SQL
Parameterised queries only — tagged templates (sql`…`, Prisma.sql), never concatenation. Wrap every multi-write invariant in a transaction, keep it short, and make no outbound HTTP call inside it. Repositories own queries; services never build SQL. Migrations are versioned files applied by the pipeline, never synchronize: true. Pool sizing and serverless pooler choices live in nodejs-performance.
7. Outbound HTTP, auth, logging, jobs
Everyfetch has a timeout: fetch(url, { signal: AbortSignal.timeout(2000) }), combined with the request's own signal through AbortSignal.any([req.signal, AbortSignal.timeout(2000)]). Retry only idempotent calls, with capped exponential backoff and jitter, honouring Retry-After; send an idempotency key when you retry a POST.
Wrap each dependency in a typed client module and parse its response with a schema — an upstream field rename should fail loudly, not flow into your database.
Auth: never roll crypto. argon2 for passwords, jose for JWT (verify signature with an alg allow-list, plus iss, aud, exp), a managed IdP or an established OAuth library. Server-side sessions in httpOnly SecureSameSite cookies are simpler and revocable for first-party web apps. Authorise per resource in the service ("may this user act on order 42?"), not only per route.
pino for logs (Fastify's built-in logger; pino-http or nestjs-pino elsewhere): JSON, a request id on every line via child loggers, and redact: ['req.headers.authorization', 'req.headers.cookie', '*.password']. No console.log in a service.
Background jobs run in a separate worker process, are idempotent, retry with backoff and have a dead-letter path (messaging-patterns).
Baseline hardening: @fastify/helmet, a CORS allow-list, rate limiting backed by Redis when multi-instance, body size limits, npm ci with a committed lockfile, non-root container user.
Generate OpenAPI from the same schemas (@fastify/swagger, @nestjs/swagger, zod-to-openapi) and publish it; contract drift is a bug (api-design).
Health endpoints, SIGTERM draining and OpenTelemetry bootstrap are owned by service-operability.
8. Deliverable format
## Summary what changed and why, in 1–3 lines
## Code full compiling TypeScript per file — schema, route, service, repository
## Errors the domain errors thrown and their status mapping
## Config new env vars, added to the config schema and .env.example
## Tests what to add and where (hand over to nodejs-testing), how to run
## Risks migrations, contract changes, rollout order
Checklist
Node, TypeScript and framework majors checked against the project's pins.
Every input parsed by a schema; types inferred from it, not written twice.
Errors are typed and mapped centrally to problem+json; no stack trace leaves the process.
No floating promises; every async path is awaited or returned.
process.env read only in the config module, validated at boot.
Every outbound call has a timeout; retries only where idempotent.
Transactions are short and contain no HTTP call.
Logs are structured with a request id and redaction; no console.log.
app.ts builds the app without listening, so tests can run it in process.
No synchronous I/O on a request path.
Anti-patterns
process.env.X outside the config module → one validated config.ts read at boot.
req.body used without a schema, or typed any → parse, then use the inferred type.
Floating promise or empty catch → await it and let the central handler see the error.
Staying alive after uncaughtException → log fatally, exit non-zero, let the orchestrator restart.
fetch with no timeout → AbortSignal.timeout, combined with the request signal.
Retrying a POST blindly → idempotency key, or do not retry.
server.listen inside app.ts → split app and server; otherwise in-process tests are impossible.
synchronize: true or migrations applied at boot by every instance → pipeline step (database-migrations).
fs.readFileSync or crypto.pbkdf2Sync on a request path → async API; the whole event loop is waiting.
z.string().url() in new Zod 4 code → z.url().
Go deeper
references/service-skeleton.md — a complete Fastify 5 service: app.ts/server.ts split, typed error classes and the problem+json handler, plugin registration, package.json scripts and a production Dockerfile.
references/data-and-http.md — Prisma 7 setup end to end (adapter, prisma.config.ts, generator output), transaction patterns, a typed outbound client with timeout, retry and idempotency key, and file upload streaming.
Sibling skills: nodejs-architecture for module boundaries, nodejs-testing for tests, nodejs-performance for symptoms, api-design for contracts, messaging-patterns, database-migrations, service-operability, backend-code-review for reviews.
---
name: nodejs-development
description: >
Build production-grade Node.js back-end services in TypeScript — framework choice (Fastify, NestJS, Express, Hono), ESM and strict tsconfig, schema validation at the edge with Zod 4 or TypeBox, typed domain errors mapped to problem+json, a validated config module, data access with Prisma 7, Drizzle or Kysely, outbound HTTP with timeouts and idempotency, auth, pino logging and background jobs. Use this whenever the user asks to write, scaffold, refactor or debug a Node/TypeScript API, route, controller, plugin, middleware or worker; edits package.json, tsconfig.json, app.ts, server.ts, main.ts, app.module.ts, prisma.config.ts or .env; asks about Zod, TypeBox, Prisma, Drizzle, Kysely, JWT, sessions, BullMQ, helmet, rate limiting or OpenAPI generation; or hits "unhandled promise rejection", "ERR_REQUIRE_ESM" or "how do I do X in Fastify/NestJS/Express". Also use it when porting a service from CommonJS to ESM. For tests use nodejs-testing; for latency or memory symptoms use nodejs-performance.
metadata:
technology: Node.js
type: development
---
# Node.js Development
> **Targets:** Node 24 LTS, TypeScript 6, ESM, Fastify 5, NestJS 12, Express 5, Zod 4, Prisma 7 · **Verified:** 2026-09 against https://nodejs.org/api/ and https://docs.nestjs.com/migration-guide
A Node service is one process multiplexing thousands of requests on one thread: anything that blocks, leaks, throws unhandled or trusts its input hurts every request at once. Write each handler assuming hostile input, a slow dependency and a `SIGTERM` arriving mid-request. **Check the project's pins first** — `engines`, `.nvmrc`, the Dockerfile base image, and the majors in `package.json` — because most of the advice below changed in a recent major.
## 1. Decide first
| Question | Default | Change when |
|---|---|---|
| Framework | **Fastify 5** — schema-first validation, fast serialisation, plugin encapsulation | Many modules and a large team → **NestJS 12**; existing Express codebase → **Express 5**; edge or multi-runtime → **Hono** |
| Modules | **ESM** (`"type": "module"`, `module: "NodeNext"`) | An existing CommonJS codebase: `require(esm)` (Node 20.19+/22.12+) lets it consume ESM dependencies during a gradual migration |
| Runtime version | Active LTS — **Node 24** (22 also LTS; **20 went EOL in March 2026**) | The project pins otherwise; NestJS 12 needs ≥ 20.19 or 22.12 to run and a newer Node for its generators |
| Validation | **Zod 4** (or TypeBox with Fastify's type provider) | NestJS: `class-validator` with `ValidationPipe`, or `StandardSchemaValidationPipe` to use Zod/Valibot |
| Error shape | RFC 9457 `application/problem+json` from one central handler | Never per-route ad-hoc JSON |
| Data access | **Prisma 7** for productivity, **Drizzle/Kysely** when you want SQL shape and types | Serverless or edge → a driver adapter plus a pooler |
| Background work | A separate worker process (BullMQ, pg-boss, Graphile Worker) | Never "fire and forget" after the response in the request process |
| Where does business logic live? | A service module the route calls | It needs a second adapter (queue consumer, CLI) → ports and adapters (`nodejs-architecture`) |
## 2. TypeScript and module setup
```jsonc
// tsconfig.json — pair with "type": "module" in package.json
{ "compilerOptions": {
"target": "ES2024", "module": "NodeNext", "moduleResolution": "NodeNext",
"strict": true, "noUncheckedIndexedAccess": true, "noImplicitOverride": true,
"verbatimModuleSyntax": true, "isolatedModules": true, "erasableSyntaxOnly": true,
"outDir": "dist", "sourceMap": true, "skipLibCheck": true } }
```
- **ESM for everything new, including NestJS 12** — its core packages ship as ESM, and `nest new` asks which you want (ESM projects get Vitest, CommonJS projects get Jest). Under `NodeNext`, relative imports carry the `.js` extension. Do not mix both module systems in one package.
- `erasableSyntaxOnly` bans the TypeScript syntax Node's built-in type stripping cannot remove (`enum`, parameter properties, namespaces), so `node --experimental-strip-types` and `tsx` keep working. It turns a runtime surprise into a compile error.
- Dev loop with `tsx` or Node's type stripping; production runs compiled JS from `dist/`. `tsc --noEmit` in CI either way.
- Layout: `src/modules/<feature>/{routes,service,repository,schemas}.ts`, plus `src/config.ts`, `src/app.ts` (builds the app, never listens) and `src/server.ts` (listens, handles signals). Splitting `app` from `server` is what makes in-process HTTP tests possible.
## 3. Validate at the edge, trust inside
Every body, query, param and header you read is parsed by a schema, and the TypeScript type is **inferred from** that schema — never a hand-written parallel interface that can drift.
```ts
import { z } from 'zod';
const CreateOrder = z.object({
sku: z.string().min(1),
qty: z.number().int().positive().max(100),
notifyUrl: z.url().optional(), // Zod 4: top-level format, not z.string().url()
});
type CreateOrder = z.infer<typeof CreateOrder>;
```
Zod 4 moved string formats to top level (`z.url()`, `z.email()`, `z.uuid()`); the chained forms still work but are legacy. Error customisation is now one `error` option: `z.string().min(5, { error: 'Too short.' })`.
Validate responses too. Fastify response schemas also **strip** unlisted fields, which is what stops a `passwordHash` reaching a client by accident.
## 4. Errors: operational versus programmer
- **Operational** (bad input, not found, conflict, dependency timeout): throw typed domain errors carrying a code; one central handler maps them to a status and a stable `application/problem+json` body. Never leak a stack trace, SQL or a driver message to a client.
- **Programmer** errors (`TypeError`, broken invariant): log with full context, return 500, fix the bug. Do not map them to a friendly 400.
- Async errors must reach the handler: Fastify and Express 5 forward rejected promises; Express 4 does not. Always `await` or `return` promises — turn on `@typescript-eslint/no-floating-promises`.
- Central handler: Fastify `setErrorHandler`, an Express 5 four-argument middleware registered last, NestJS exception filters.
- At process level, log fatally on `uncaughtException` and `unhandledRejection` and **exit non-zero**. Continuing runs the service in an unknown state; let the orchestrator restart it.
## 5. Config and secrets
```ts
// src/config.ts — the only file that reads process.env
import { z } from 'zod';
const Env = z.object({
NODE_ENV: z.enum(['development', 'test', 'production']),
PORT: z.coerce.number().default(3000),
DATABASE_URL: z.url(),
JWT_ISSUER: z.url(),
});
export const config = Env.parse(process.env); // fails at boot with a readable message
```
Inject `config` or slices of it. `process.env.X` scattered through modules is unvalidated and untestable. `.env` is for local development only (`node --env-file=.env`), git-ignored, with a committed `.env.example`; deployed secrets come from the platform's secret store. Note that **Prisma 7 no longer loads `.env` automatically** — load it explicitly in `prisma.config.ts`.
## 6. Data access
| Tool | Choose when | Watch |
|---|---|---|
| **Prisma 7** | Schema-first migrations, typed client, speed of delivery | v7 requires a driver adapter per database, is ESM-only, needs `output` in the generator block and a `prisma.config.ts` (`references/data-and-http.md`) |
| **Drizzle** | You want the SQL shape visible and types inferred | Younger ecosystem; you design more yourself |
| **Kysely / Knex** | Full SQL control, Kysely for types | You own mapping and migration discipline |
| **TypeORM / MikroORM** | The team wants entity and unit-of-work patterns (often with NestJS) | Lazy loading and N+1; read the generated SQL |
Parameterised queries only — tagged templates (`` sql`…` ``, `Prisma.sql`), never concatenation. Wrap every multi-write invariant in a transaction, keep it short, and make no outbound HTTP call inside it. Repositories own queries; services never build SQL. Migrations are versioned files applied by the pipeline, never `synchronize: true`. Pool sizing and serverless pooler choices live in `nodejs-performance`.
## 7. Outbound HTTP, auth, logging, jobs
- **Every** `fetch` has a timeout: `fetch(url, { signal: AbortSignal.timeout(2000) })`, combined with the request's own signal through `AbortSignal.any([req.signal, AbortSignal.timeout(2000)])`. Retry only idempotent calls, with capped exponential backoff and jitter, honouring `Retry-After`; send an idempotency key when you retry a POST.
- Wrap each dependency in a typed client module and **parse its response with a schema** — an upstream field rename should fail loudly, not flow into your database.
- Auth: never roll crypto. `argon2` for passwords, `jose` for JWT (verify signature with an `alg` allow-list, plus `iss`, `aud`, `exp`), a managed IdP or an established OAuth library. Server-side sessions in httpOnly `Secure` `SameSite` cookies are simpler and revocable for first-party web apps. Authorise **per resource** in the service ("may this user act on order 42?"), not only per route.
- **pino** for logs (Fastify's built-in logger; `pino-http` or `nestjs-pino` elsewhere): JSON, a request id on every line via child loggers, and `redact: ['req.headers.authorization', 'req.headers.cookie', '*.password']`. No `console.log` in a service.
- Background jobs run in a **separate worker process**, are idempotent, retry with backoff and have a dead-letter path (`messaging-patterns`).
- Baseline hardening: `@fastify/helmet`, a CORS allow-list, rate limiting backed by Redis when multi-instance, body size limits, `npm ci` with a committed lockfile, non-root container user.
- Generate OpenAPI from the same schemas (`@fastify/swagger`, `@nestjs/swagger`, `zod-to-openapi`) and publish it; contract drift is a bug (`api-design`).
Health endpoints, `SIGTERM` draining and OpenTelemetry bootstrap are owned by `service-operability`.
## 8. Deliverable format
```
## Summary what changed and why, in 1–3 lines
## Code full compiling TypeScript per file — schema, route, service, repository
## Errors the domain errors thrown and their status mapping
## Config new env vars, added to the config schema and .env.example
## Tests what to add and where (hand over to nodejs-testing), how to run
## Risks migrations, contract changes, rollout order
```
## Checklist
- [ ] Node, TypeScript and framework majors checked against the project's pins.
- [ ] Every input parsed by a schema; types inferred from it, not written twice.
- [ ] Errors are typed and mapped centrally to problem+json; no stack trace leaves the process.
- [ ] No floating promises; every async path is awaited or returned.
- [ ] `process.env` read only in the config module, validated at boot.
- [ ] Every outbound call has a timeout; retries only where idempotent.
- [ ] Transactions are short and contain no HTTP call.
- [ ] Logs are structured with a request id and redaction; no `console.log`.
- [ ] `app.ts` builds the app without listening, so tests can run it in process.
- [ ] No synchronous I/O on a request path.
## Anti-patterns
- **`process.env.X` outside the config module** → one validated `config.ts` read at boot.
- **`req.body` used without a schema, or typed `any`** → parse, then use the inferred type.
- **Floating promise or empty `catch`** → await it and let the central handler see the error.
- **Staying alive after `uncaughtException`** → log fatally, exit non-zero, let the orchestrator restart.
- **`fetch` with no timeout** → `AbortSignal.timeout`, combined with the request signal.
- **Retrying a POST blindly** → idempotency key, or do not retry.
- **`server.listen` inside `app.ts`** → split `app` and `server`; otherwise in-process tests are impossible.
- **`synchronize: true` or migrations applied at boot by every instance** → pipeline step (`database-migrations`).
- **`fs.readFileSync` or `crypto.pbkdf2Sync` on a request path** → async API; the whole event loop is waiting.
- **`z.string().url()` in new Zod 4 code** → `z.url()`.
## Go deeper
- `references/service-skeleton.md` — a complete Fastify 5 service: `app.ts`/`server.ts` split, typed error classes and the problem+json handler, plugin registration, `package.json` scripts and a production Dockerfile.
- `references/data-and-http.md` — Prisma 7 setup end to end (adapter, `prisma.config.ts`, generator `output`), transaction patterns, a typed outbound client with timeout, retry and idempotency key, and file upload streaming.
- Sibling skills: `nodejs-architecture` for module boundaries, `nodejs-testing` for tests, `nodejs-performance` for symptoms, `api-design` for contracts, `messaging-patterns`, `database-migrations`, `service-operability`, `backend-code-review` for reviews.