Node.js and TypeScript back ends¶
Scope: server-side services that run on Node.js and are written in TypeScript, such as HTTP APIs, workers and scheduled jobs. For configuration, health checks, telemetry and resilience, follow general/operations-reliability.md; for secrets, authorization and the supply chain, follow general/security.md. The rules here cover what is specific to Node.js and TypeScript.
Entries are sorted by score from 1 to 10 (criteria): 9โ10 start here or strongly recommended, 6โ8 recommended, 1โ5 further reading or conditional.
Adopted references¶
- 9 Don't Block the Event Loop (or the Worker Pool) (Node.js): how Node.js runs many clients on a few threads, and how to keep each callback and task small. Read it before designing a service.
- 9 Security Best Practices (Node.js): Node.js-specific threats, such as HTTP denial of service, malicious dependencies and prototype pollution, with mitigations for each.
- 7 Node.js Best Practices (Yoni Goldberg and contributors): the largest community collection, covering project structure, error handling, testing, production, security and Docker. Use it as a checklist; it isn't an official source.
Key rules¶
- 9
NODE-1Don't block the event loop. In request paths, don't call the synchronous file system, crypto, compression or child-process APIs, and either split CPU-heavy work into small steps or move it off the event loop, to a worker pool or a dedicated service. (Node.js, Don't Block the Event Loop, Node.js Best Practices 7.1) - 8
NODE-2Await or return every promise, and don't pass async functions where the caller ignores the returned promise. Since Node.js 15, an unhandled rejection crashes the process by default. This is how Node.js code appliesPRIN-16. (typescript-eslint, no-floating-promises, no-misused-promises, Node.js CLI, --unhandled-rejections) - 8
NODE-3Validate all external input, such as request bodies, query strings and messages, at runtime with a schema library. TypeScript types are erased before the code runs, so they don't check incoming data; schema validation also guards against prototype pollution. (Node.js Best Practices 6.10, 2.11, TypeScript, Erased types, Node.js, Prototype pollution) - 8
NODE-4Commit the lockfile, install withnpm ci, and check dependencies for known vulnerabilities in CI. Consider--ignore-scriptsand a minimum release age to reduce exposure to malicious packages. See general/security.md for provenance and dependency updates. (Node.js, Supply chain attacks, npm ci, Node.js Best Practices 5.19) - 8
NODE-5Run only Active LTS or Maintenance LTS releases of Node.js in production. (Node.js, Releases, Node.js Best Practices 5.17) - 7
NODE-6Treat unknown errors as fatal: log them, shut down gracefully and let the platform restart the process. UseuncaughtExceptiononly for synchronous cleanup before exiting, because the app is in an undefined state. (Node.js, Using 'uncaughtException' correctly, Node.js Best Practices 2.3, 2.6) - 7
NODE-7Structure the service by business components, each with its own entry points, domain logic and data access, and keep web-framework objects out of the domain logic. (Node.js Best Practices 1.1, 1.2) - 7
NODE-8Type-check Node.js services in CI withtsc, and setmoduletonodenext. Node.js runs TypeScript by stripping the types without checking them, so onlytsccatches type errors, andnodenextmakes the compiler resolve imports the way Node.js does. The compiler settings for any TypeScript codebase areTS-1,TS-2andTS-5in TypeScript. (TypeScript, strict, Node.js, Modules: TypeScript, TypeScript, Choosing compiler options) - 7
NODE-9Shut down gracefully onSIGTERM: fail the readiness check, stop accepting connections, finish in-flight requests, close resources, then exit. Start the process withnode, notnpm start, so that it receives the signal. (Node.js Best Practices 8.6, 8.2, Node.js, server.close(), Kubernetes, Pod lifecycle) - 7
NODE-10Log structured JSON to stdout with a mature logger such as Pino, add request context with child loggers, and redact secrets. Let the platform route the logs, and keep sensitive data out of them as general/security.md requires. (Node.js Best Practices 2.7, 5.18, Pino, Child loggers, Pino, Redaction) - 6
NODE-11Handle errors in one central handler that every entry point (HTTP routes, jobs, message consumers) calls, and throw onlyErrorobjects or subclasses of it. (Node.js Best Practices 2.4, 2.2) - 6
NODE-12Set HTTP server timeouts and connection limits, and put a reverse proxy in front of the service. Idle or slow connections otherwise hold resources and enable denial of service. (Node.js, Denial of service of HTTP server)
How to enforce¶
Tools that check the key rules above automatically, in CI, the IDE or a commit hook. "Partly" means the tool covers only some of what the rule asks.
- 7 TypeScript
strict: withstricton, runningtsc --noEmitin CI fails the build on type errors. ChecksNODE-8. - 7 typescript-eslint
no-floating-promisesandno-misused-promises: type-aware lint rules, both inrecommended-type-checked, that flag unhandled promises and promises passed where they aren't handled. ChecksNODE-2, and partlyPRIN-16. - 7 npm ci and npm audit:
npm cifails whenpackage.jsonand the lockfile disagree, andnpm audit --audit-level=<level>fails on known vulnerabilities. Pair them with Dependabot (general/security.md). Partly checksNODE-4. - 6 eslint-plugin-n
no-sync: flags calls to synchronous*Syncmethods. Partly checksNODE-1. - 6 eslint-plugin-regexp
no-super-linear-backtracking: flags regular expressions with exponential or polynomial backtracking (ReDoS), which block the event loop. Partly checksNODE-1. - 6 dependency-cruiser:
forbiddenrules with group matching stop one business component from importing another's internals, and fail CI on violations. Partly checksNODE-7.
Tutorials and further reading¶
- 9 The TypeScript Handbook (TypeScript): the official guide to the language and its type system.
- 7 Node.js Design Patterns (Mario Casciaro and Luciano Mammino, 4th edition): asynchronous programming, streams, design patterns, testing, and scaling with microservices and messaging.