Node.js Cookbook
“How would you do X?” — practical, production-ready recipes with the approach, full code, pitfalls and variations.
Node.js
- Add health and readiness endpoints to a Node.js serviceLet Kubernetes restart stuck processes and route traffic only to instances that can serve it.
- Add JWT authentication to an Express APIProtect Express routes with bearer tokens and expose the authenticated user to handlers.
- Cache expensive lookups in Redis from Node.jsReduce database load for a hot endpoint while avoiding stampedes when entries expire.
- Call external APIs with timeouts and retries in Node.jsMake outbound HTTP calls that never hang and recover from transient failures.
- Centralize error handling in Express 5Return consistent error responses and never leak stack traces, including for async handler failures.
- Hash passwords and implement login safely in Node.jsStore user passwords securely and build a login endpoint resistant to brute force and enumeration.
- Implement cursor pagination with PostgreSQL in Node.jsPaginate an activity feed efficiently with node-postgres, without OFFSET.
- Offload CPU-heavy work with worker threadsKeep an Express API responsive while generating PDFs or hashing large files.
- Process background jobs with BullMQSend emails and generate thumbnails outside the request cycle with retries and concurrency control.
- Rate limit an Express API across instancesThrottle login attempts and API calls per client, shared across all Node processes.
- Run database transactions correctly with node-postgresTransfer money between accounts atomically and avoid leaking pooled connections.
- Scale real-time Socket.IO across instancesBroadcast chat messages to rooms when users are connected to different Node instances.
- Shut down a Node.js server gracefullyDeploy without dropping in-flight requests or leaving database connections and jobs half-done.
- Stream a large CSV export in Node.jsExport millions of database rows as CSV without loading them into memory.
- Structured logging with request IDs in Node.jsProduce fast JSON logs where every line from a request carries the same request ID.
- Test an Express API with node:test and supertestWrite fast API tests without a separate test framework, including auth and validation cases.
- Upload files to S3 with presigned URLs from Node.jsLet clients upload large files directly to S3 while the API controls keys, types and sizes.
- Validate environment configuration at startupFail fast with a clear message when an env variable is missing or malformed, and get typed config.
- Validate Express requests with ZodReject invalid bodies and query strings with clear 422 errors and get typed data in handlers.
- Verify webhook signatures in ExpressAccept signed webhooks safely: verify the raw body, prevent replays and drop duplicates.