🟢

Node.js

Production-ready Node.js snippets for APIs, authentication, file I/O, and more.

100 snippets

Showing 100 of 100 snippets

typescriptintermediate

JWT Verify Middleware

Express middleware that verifies JWT tokens from the Authorization header and attaches the decoded payload to the request.

Best for: REST API authentication

#jwt#express
typescriptintermediate

In-Memory Rate Limiter for Express

Token bucket rate limiter middleware for Express with configurable window and max requests per IP.

Best for: API abuse prevention

#express#rate-limit
typescriptbeginner

Async Error Handler Wrapper

Higher-order function that wraps async Express route handlers and forwards rejected promises to error middleware.

Best for: Express route error handling

#express#async
typescriptbeginner

Environment Variable Validator

Validates required environment variables at startup and returns a typed config object or throws with missing keys.

Best for: App startup validation

#config#validation
typescriptintermediate

File Upload with Multer

Configure Multer for disk storage with file type validation, size limits, and unique filenames for Express.

Best for: Profile avatar uploads

#express#upload
typescriptintermediate

HTTP Client with Axios Interceptors

Pre-configured Axios instance with request/response interceptors for auth headers, logging, and retry logic.

Best for: Consuming third-party APIs

#axios#http
typescriptadvanced

Redis Cache Get/Set Helper

Type-safe Redis cache wrapper with automatic JSON serialization, TTL support, and cache-aside pattern.

Best for: Database query caching

#redis#cache
typescriptadvanced

Graceful Server Shutdown

Handle SIGTERM and SIGINT signals to drain connections, close database pools, and exit cleanly.

Best for: Production server deployment

#server#shutdown
typescriptadvanced

Stream File Download

Express handler that streams a file to the client with proper headers, range support, and error handling.

Best for: Large file downloads

#stream#download
typescriptbeginner

UUID and Nano ID Generator

Generate RFC-4122 v4 UUIDs and URL-safe nano IDs using the Node.js built-in crypto module with zero deps.

Best for: Database primary keys

#uuid#crypto
typescriptintermediate

Prisma Find with Relations

Query related records using Prisma ORM include and select for efficient nested data loading.

Best for: Loading user profiles with posts

#prisma#orm
typescriptintermediate

Bull Queue Job Producer & Consumer

Create a job queue with Bull for background processing with retries and concurrency control.

Best for: Email sending queue

#queue#bull
typescriptbeginner

Express Zod Request Validation

Validate Express request body, params, and query with Zod schemas via reusable middleware.

Best for: API input validation

#express#zod
typescriptbeginner

Nodemailer Send Email with SMTP

Send transactional emails using Nodemailer with SMTP transport, HTML templates, and attachments.

Best for: Welcome emails

#email#nodemailer
typescriptbeginner

Node.js Cron Job Scheduler

Schedule recurring tasks with node-cron using crontab syntax and timezone support.

Best for: Database cleanup tasks

#cron#scheduler
typescriptintermediate

WebSocket Server with ws

Create a WebSocket server with connection tracking, heartbeat ping/pong, and typed message handling.

Best for: Chat applications

#websocket#realtime
typescriptadvanced

JWT Refresh Token Rotation

Implement secure token rotation with short-lived access tokens and one-time-use refresh tokens.

Best for: Secure API authentication

#jwt#authentication
typescriptbeginner

Bcrypt Password Hash & Verify

Hash and verify passwords with bcrypt using configurable salt rounds and timing-safe comparison.

Best for: User registration

#bcrypt#password
typescriptintermediate

CSV Parse with Streaming

Parse large CSV files using Node.js streams with row-by-row processing and backpressure handling.

Best for: Data import pipelines

#csv#stream
typescriptintermediate

S3 Presigned URL Generator

Generate secure presigned URLs for S3 upload and download operations with expiry and content type.

Best for: Direct browser uploads

#aws#s3
typescriptadvanced

Node.js Worker Threads for Parallel Processing

Use Worker Threads to run CPU-intensive tasks in parallel without blocking the event loop.

Best for: CPU-intensive data processing without blocking

#nodejs#worker-threads
typescriptintermediate

Node.js Stream Pipeline with Transform

Build efficient data processing pipelines using Node.js streams for large file handling.

Best for: Processing large CSV files without loading into memory

#nodejs#streams
typescriptintermediate

TypeScript Typed Event Emitter

Create type-safe event emitters in Node.js with full TypeScript support and autocomplete.

Best for: Type-safe pub/sub communication between modules

#nodejs#events
typescriptintermediate

Node.js Graceful Shutdown Handler

Implement graceful shutdown to properly close connections and finish requests before exit.

Best for: Production Node.js server reliability

#nodejs#shutdown
typescriptintermediate

Node.js Crypto Utility Functions

Common cryptographic operations: hashing, HMAC, encryption, random tokens, and password hashing.

Best for: Secure password storage and verification

#nodejs#crypto
typescriptintermediate

Node.js Recursive File Watcher

Watch files and directories for changes with debouncing and glob pattern filtering.

Best for: Custom hot-reload during development

#nodejs#file-system
typescriptadvanced

Node.js Cluster Mode for Scaling

Scale Node.js across CPU cores using the cluster module with automatic worker respawning.

Best for: Utilizing all CPU cores for HTTP servers

#nodejs#cluster
typescriptintermediate

Request Validation Schema Builder

Build a lightweight request validation layer with type inference for API endpoints.

Best for: API request body validation

#nodejs#validation
typescriptadvanced

Node.js In-Memory Task Queue

A simple in-memory task queue with concurrency control, retries, and priority support.

Best for: Rate-limited API call processing

#nodejs#queue
typescriptintermediate

Node.js Token Bucket Rate Limiter

Implement an in-memory token bucket rate limiter for controlling API request throughput.

Best for: Protecting APIs from abuse and DDoS

#nodejs#rate-limiting
typescriptbeginner

Read and Write JSON Files

Read, parse, modify, and write JSON files with proper error handling using Node.js fs module.

Best for: Configuration file management

#nodejs#json
typescriptbeginner

Cross-Platform Path Operations

Use Node.js path module for cross-platform file path manipulation, resolution, and normalization.

Best for: Cross-platform file path handling

#nodejs#path
typescriptintermediate

Child Process: exec and spawn

Execute shell commands and spawn processes with exec, execFile, spawn, and fork in Node.js.

Best for: Running shell commands from Node.js

#nodejs#child-process
typescriptbeginner

Native HTTP Server

Create a lightweight HTTP server using Node.js built-in http module with routing and JSON responses.

Best for: Lightweight API server without frameworks

#nodejs#http
typescriptintermediate

Event Loop and Timers

Understand Node.js event loop phases with setTimeout, setInterval, setImmediate, and process.nextTick.

Best for: Understanding async execution order

#nodejs#event-loop
typescriptadvanced

Streams: Readable, Writable, Transform

Build custom readable, writable, and transform streams for efficient data processing in Node.js.

Best for: Processing large files without loading into memory

#nodejs#streams
typescriptbeginner

Custom Error Classes

Create typed custom error classes with HTTP status codes, error codes, and structured error handling.

Best for: Structured API error responses

#nodejs#error
typescriptintermediate

Middleware Pattern and Composition

Implement the middleware pattern for composable request processing with next() and error handling.

Best for: Request processing pipelines

#nodejs#middleware
typescriptintermediate

Promise Concurrency Patterns

Master Promise.all, allSettled, race, any — parallel execution with error handling and timeouts.

Best for: Parallel API calls with error handling

#nodejs#promise
typescriptbeginner

Directory Operations with fs

Create, read, copy, and remove directories recursively using Node.js fs/promises.

Best for: Build tool directory management

#nodejs#fs
typescriptintermediate

Compression with zlib

Compress and decompress data using gzip, deflate, and brotli with Node.js built-in zlib module.

Best for: API response compression

#nodejs#zlib
typescriptbeginner

URL and Query String Parsing

Parse, construct, and manipulate URLs and query strings using the Node.js URL and URLSearchParams API.

Best for: API URL construction

#nodejs#url
typescriptintermediate

Process Signals and Environment

Handle process signals, environment variables, exit codes, and unhandled errors in Node.js.

Best for: Graceful server shutdown

#nodejs#process
typescriptintermediate

Buffer and Binary Data

Work with binary data using Node.js Buffer: create, convert, slice, encode/decode, and compare.

Best for: Binary protocol implementation

#nodejs#buffer
typescriptbeginner

Native Test Runner and Assert

Write tests using Node.js built-in test runner and assert module — no external dependencies needed.

Best for: Unit testing without external packages

#nodejs#testing
typescriptintermediate

Crypto Hashing and HMAC

Generate secure hashes, HMACs, and checksums using Node.js built-in crypto module.

Best for: Webhook signature verification

#nodejs#crypto
typescriptadvanced

AbortController for Cancellation

Cancel async operations with AbortController: fetch requests, timers, streams, and custom operations.

Best for: Request timeout handling

#nodejs#abort
typescriptadvanced

Performance Measurement

Measure execution time with performance.now(), Performance API marks, measures, and PerformanceObserver.

Best for: Function execution profiling

#nodejs#performance
typescriptadvanced

Typed Event Emitter Class

Build a type-safe event emitter with TypeScript generics for strongly-typed event handling.

Best for: Type-safe event-driven architecture

#nodejs#events
typescriptbeginner

Interactive CLI with Readline

Build interactive command-line interfaces using Node.js readline with prompts, history, and auto-completion.

Best for: Building simple CLI tools

#nodejs#readline
typescriptbeginner

DNS Lookup and Resolution

Perform DNS lookups, resolve hostnames to IP addresses, and query DNS records using Node.js dns module.

Best for: Network diagnostics tools

#nodejs#dns
typescriptbeginner

System Information with OS Module

Retrieve system information including CPU, memory, network interfaces, and platform details using os module.

Best for: Server health dashboards

#nodejs#os
typescriptadvanced

HTTP/2 Server with Stream Push

Create an HTTP/2 server with server push, multiplexed streams, and TLS configuration in Node.js.

Best for: High-performance web servers

#nodejs#http2
typescriptadvanced

Async Iterators for Stream Processing

Process streams and async data sources with for-await-of loops and custom async iterators in Node.js.

Best for: Paginated API data consumption

#nodejs#async-iterator
typescriptadvanced

Cluster Worker Pool Pattern

Distribute CPU-intensive tasks across worker processes with automatic restart and load balancing.

Best for: Multi-core CPU utilization

#nodejs#cluster
typescriptadvanced

TCP Server and Client with Net Module

Build TCP server and client pairs using Node.js net module with connection pooling and message framing.

Best for: Custom protocol implementation

#nodejs#tcp
typescriptintermediate

Event-Driven Architecture Pattern

Build loosely coupled systems with typed event bus, async event handlers, and domain event patterns.

Best for: Microservice communication

#nodejs#events
typescriptadvanced

JavaScript Proxy Handler Pattern

Use Proxy and Reflect to create observable objects, validation layers, and dynamic API clients.

Best for: Observable state management

#nodejs#proxy
typescriptintermediate

Schema Validation with Zod-like Patterns

Build a minimal schema validation library inspired by Zod using TypeScript type inference.

Best for: API request validation

#nodejs#validation
typescriptintermediate

Express Error Handling Middleware

Centralized error handling in Express with custom error classes, async wrapper, and structured responses.

Best for: API error standardization

#nodejs#express
typescriptadvanced

Dependency Injection Container

Build a lightweight DI container with singleton and transient scopes for testable Node.js applications.

Best for: Testable application architecture

#nodejs#dependency-injection
typescriptintermediate

Semaphore for Concurrency Limiting

Control concurrent async operations with a semaphore pattern: rate limiting, connection pooling, and batch processing.

Best for: API rate limiting

#nodejs#concurrency
typescriptintermediate

In-Memory Caching with LRU Strategy

Implement LRU cache with TTL expiration, size limits, and cache-aside pattern for Node.js applications.

Best for: API response caching

#nodejs#caching
typescriptintermediate

Retry with Exponential Backoff

Retry failed async operations with exponential backoff, jitter, and configurable retry conditions.

Best for: API call resilience

#nodejs#retry
typescriptintermediate

Promise Pool for Batch Processing

Process large arrays with controlled concurrency using a promise pool pattern with progress tracking.

Best for: Bulk API requests

#nodejs#promise
typescriptbeginner

Type-Safe Configuration Loader

Load and validate configuration from environment variables with type coercion and required field checks.

Best for: Application configuration management

#nodejs#config
typescriptbeginner

Structured JSON Logger

Build a structured logger with log levels, context, child loggers, and JSON output for Node.js services.

Best for: Application logging for production

#nodejs#logging
typescriptintermediate

Middleware Chain Pattern

Implement the middleware/pipeline pattern for composable request processing without Express.

Best for: Custom HTTP framework

#nodejs#middleware
typescriptbeginner

Fastify Server Setup

Create a high-performance Fastify server with schema validation, plugins, and typed routes.

Best for: High-performance REST APIs

#nodejs#fastify
typescriptbeginner

CORS Configuration Middleware

Configure Cross-Origin Resource Sharing with origin allowlists, credentials, and preflight handling.

Best for: API CORS configuration

#nodejs#cors
typescriptintermediate

Secure Cookie and Session Management

Handle HTTP cookies with signing, encryption, and session management using secure defaults.

Best for: Authentication session handling

#nodejs#cookies
typescriptadvanced

GraphQL Server with Type Definitions

Build a GraphQL API server with type definitions, resolvers, and query/mutation support.

Best for: GraphQL API development

#nodejs#graphql
typescriptbeginner

Health Check Endpoint Pattern

Implement comprehensive health checks with dependency status, uptime, and readiness probes.

Best for: Kubernetes liveness probes

#nodejs#health-check
typescriptintermediate

Webhook Handler with Signature Verification

Process incoming webhooks with HMAC signature verification, replay protection, and idempotency.

Best for: GitHub/Stripe webhook processing

#nodejs#webhook
typescriptintermediate

Cursor-Based Pagination API

Implement cursor-based pagination with forward/backward navigation, consistent ordering, and link headers.

Best for: REST API pagination

#nodejs#pagination
typescriptintermediate

API Versioning Strategy

Implement API versioning with URL path, header-based, and content negotiation strategies.

Best for: API backward compatibility

#nodejs#api
typescriptadvanced

Debug with Inspector Protocol

Programmatic debugging with Node.js inspector module for heap snapshots, CPU profiling, and breakpoints.

Best for: Production performance profiling

#nodejs#debugging
typescriptbeginner

ESM and CJS Module Interop

Handle ECMAScript module and CommonJS interop with dynamic imports, conditional exports, and dual packages.

Best for: Library dual packaging

#nodejs#esm
typescriptadvanced

Application Metrics Collection

Collect and expose application metrics like request counts, latency histograms, and custom gauges.

Best for: Prometheus metrics endpoint

#nodejs#monitoring
typescriptintermediate

Pub/Sub Messaging Pattern

Implement publish/subscribe messaging with topics, filtered subscriptions, and message replay.

Best for: In-process event messaging

#nodejs#pubsub
typescriptintermediate

Request ID Tracing Middleware

Express middleware that generates or forwards X-Request-Id headers for distributed tracing.

Best for: Distributed tracing

#express#tracing
typescriptintermediate

ETag Caching Middleware

Express middleware that generates ETags and handles 304 Not Modified responses for bandwidth savings.

Best for: API caching

#express#caching
typescriptadvanced

Circuit Breaker Pattern

Implements the circuit breaker pattern to prevent cascading failures when calling external services.

Best for: External API calls

#resilience#microservices
typescriptintermediate

IP Geolocation Middleware

Extracts client IP and attaches geolocation data to the request using a lightweight lookup.

Best for: Content localization

#express#geolocation
typescriptintermediate

Response Compression Middleware

Native zlib-based middleware that gzip-compresses responses above a size threshold.

Best for: Reducing API payload size

#express#compression
typescriptbeginner

Request Timeout Middleware

Express middleware that aborts requests exceeding a configurable time limit with 408 status.

Best for: Preventing hanging requests

#express#timeout
typescriptbeginner

API Key Authentication Middleware

Simple API key validation middleware that checks the X-API-Key header against a set of valid keys.

Best for: Public API authentication

#express#authentication
typescriptadvanced

Multipart Upload Stream Handler

Handles multipart file uploads with streaming to disk without buffering the entire file in memory.

Best for: Large file uploads

#upload#streaming
typescriptadvanced

Graceful HTTP Server Shutdown

Production-ready server shutdown that drains active connections and closes resources cleanly.

Best for: Container deployments

#server#shutdown
typescriptbeginner

Structured Request Logger Middleware

Express middleware that logs request/response details as structured JSON with timing information.

Best for: API monitoring

#express#logging
typescriptadvanced

Promise Queue with Concurrency Limit

A queue that processes async tasks with a configurable concurrency limit to prevent resource exhaustion.

Best for: Rate-limited API calls

#async#concurrency
typescriptbeginner

Environment Secrets Loader

Loads and validates required environment variables at startup and throws meaningful errors for missing ones.

Best for: Application bootstrap

#env#config
typescriptintermediate

Server-Sent Events Handler

Express route that implements SSE for real-time server-to-client push notifications.

Best for: Live notifications

#sse#real-time
typescriptintermediate

In-Memory Response Cache

Simple TTL-based in-memory cache middleware for GET endpoints that serves cached responses.

Best for: Caching expensive queries

#cache#performance
typescriptadvanced

Idempotency Key Middleware

Prevents duplicate request processing by caching responses keyed by the Idempotency-Key header.

Best for: Payment processing

#idempotency#api
typescriptadvanced

OpenAPI Request Validator

Validates incoming request body against a JSON schema derived from an OpenAPI spec.

Best for: API input validation

#openapi#validation
typescriptintermediate

Webhook Signature Verification

Verifies HMAC-SHA256 webhook signatures to ensure payloads are from trusted sources.

Best for: GitHub webhook handlers

#webhook#security
typescriptadvanced

JSON Stream Parser

Parses large JSON arrays from a readable stream without loading the entire file into memory.

Best for: Processing large log files

#streaming#json
typescriptintermediate

Health, Readiness & Liveness Checks

Express routes implementing Kubernetes-style health, readiness, and liveness probe endpoints.

Best for: Kubernetes deployments

#health-check#kubernetes
typescriptadvanced

Sliding Window Rate Limiter

Implements sliding window rate limiting that distributes limits more evenly than fixed windows.

Best for: API rate limiting

#rate-limiting#security