Node.js
Production-ready Node.js snippets for APIs, authentication, file I/O, and more.
100 snippets
Showing 100 of 100 snippets
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
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
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
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
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
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
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
Graceful Server Shutdown
Handle SIGTERM and SIGINT signals to drain connections, close database pools, and exit cleanly.
Best for: Production server deployment
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
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
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
Bull Queue Job Producer & Consumer
Create a job queue with Bull for background processing with retries and concurrency control.
Best for: Email sending queue
Express Zod Request Validation
Validate Express request body, params, and query with Zod schemas via reusable middleware.
Best for: API input validation
Nodemailer Send Email with SMTP
Send transactional emails using Nodemailer with SMTP transport, HTML templates, and attachments.
Best for: Welcome emails
Node.js Cron Job Scheduler
Schedule recurring tasks with node-cron using crontab syntax and timezone support.
Best for: Database cleanup tasks
WebSocket Server with ws
Create a WebSocket server with connection tracking, heartbeat ping/pong, and typed message handling.
Best for: Chat applications
JWT Refresh Token Rotation
Implement secure token rotation with short-lived access tokens and one-time-use refresh tokens.
Best for: Secure API authentication
Bcrypt Password Hash & Verify
Hash and verify passwords with bcrypt using configurable salt rounds and timing-safe comparison.
Best for: User registration
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
S3 Presigned URL Generator
Generate secure presigned URLs for S3 upload and download operations with expiry and content type.
Best for: Direct browser uploads
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
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
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
Node.js Graceful Shutdown Handler
Implement graceful shutdown to properly close connections and finish requests before exit.
Best for: Production Node.js server reliability
Node.js Crypto Utility Functions
Common cryptographic operations: hashing, HMAC, encryption, random tokens, and password hashing.
Best for: Secure password storage and verification
Node.js Recursive File Watcher
Watch files and directories for changes with debouncing and glob pattern filtering.
Best for: Custom hot-reload during development
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
Request Validation Schema Builder
Build a lightweight request validation layer with type inference for API endpoints.
Best for: API request body validation
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
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
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
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
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
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
Event Loop and Timers
Understand Node.js event loop phases with setTimeout, setInterval, setImmediate, and process.nextTick.
Best for: Understanding async execution order
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
Custom Error Classes
Create typed custom error classes with HTTP status codes, error codes, and structured error handling.
Best for: Structured API error responses
Middleware Pattern and Composition
Implement the middleware pattern for composable request processing with next() and error handling.
Best for: Request processing pipelines
Promise Concurrency Patterns
Master Promise.all, allSettled, race, any — parallel execution with error handling and timeouts.
Best for: Parallel API calls with error handling
Directory Operations with fs
Create, read, copy, and remove directories recursively using Node.js fs/promises.
Best for: Build tool directory management
Compression with zlib
Compress and decompress data using gzip, deflate, and brotli with Node.js built-in zlib module.
Best for: API response compression
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
Process Signals and Environment
Handle process signals, environment variables, exit codes, and unhandled errors in Node.js.
Best for: Graceful server shutdown
Buffer and Binary Data
Work with binary data using Node.js Buffer: create, convert, slice, encode/decode, and compare.
Best for: Binary protocol implementation
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
Crypto Hashing and HMAC
Generate secure hashes, HMACs, and checksums using Node.js built-in crypto module.
Best for: Webhook signature verification
AbortController for Cancellation
Cancel async operations with AbortController: fetch requests, timers, streams, and custom operations.
Best for: Request timeout handling
Performance Measurement
Measure execution time with performance.now(), Performance API marks, measures, and PerformanceObserver.
Best for: Function execution profiling
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
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
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
System Information with OS Module
Retrieve system information including CPU, memory, network interfaces, and platform details using os module.
Best for: Server health dashboards
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
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
Cluster Worker Pool Pattern
Distribute CPU-intensive tasks across worker processes with automatic restart and load balancing.
Best for: Multi-core CPU utilization
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
Event-Driven Architecture Pattern
Build loosely coupled systems with typed event bus, async event handlers, and domain event patterns.
Best for: Microservice communication
JavaScript Proxy Handler Pattern
Use Proxy and Reflect to create observable objects, validation layers, and dynamic API clients.
Best for: Observable state management
Schema Validation with Zod-like Patterns
Build a minimal schema validation library inspired by Zod using TypeScript type inference.
Best for: API request validation
Express Error Handling Middleware
Centralized error handling in Express with custom error classes, async wrapper, and structured responses.
Best for: API error standardization
Dependency Injection Container
Build a lightweight DI container with singleton and transient scopes for testable Node.js applications.
Best for: Testable application architecture
Semaphore for Concurrency Limiting
Control concurrent async operations with a semaphore pattern: rate limiting, connection pooling, and batch processing.
Best for: API rate limiting
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
Retry with Exponential Backoff
Retry failed async operations with exponential backoff, jitter, and configurable retry conditions.
Best for: API call resilience
Promise Pool for Batch Processing
Process large arrays with controlled concurrency using a promise pool pattern with progress tracking.
Best for: Bulk API requests
Type-Safe Configuration Loader
Load and validate configuration from environment variables with type coercion and required field checks.
Best for: Application configuration management
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
Middleware Chain Pattern
Implement the middleware/pipeline pattern for composable request processing without Express.
Best for: Custom HTTP framework
Fastify Server Setup
Create a high-performance Fastify server with schema validation, plugins, and typed routes.
Best for: High-performance REST APIs
CORS Configuration Middleware
Configure Cross-Origin Resource Sharing with origin allowlists, credentials, and preflight handling.
Best for: API CORS configuration
Secure Cookie and Session Management
Handle HTTP cookies with signing, encryption, and session management using secure defaults.
Best for: Authentication session handling
GraphQL Server with Type Definitions
Build a GraphQL API server with type definitions, resolvers, and query/mutation support.
Best for: GraphQL API development
Health Check Endpoint Pattern
Implement comprehensive health checks with dependency status, uptime, and readiness probes.
Best for: Kubernetes liveness probes
Webhook Handler with Signature Verification
Process incoming webhooks with HMAC signature verification, replay protection, and idempotency.
Best for: GitHub/Stripe webhook processing
Cursor-Based Pagination API
Implement cursor-based pagination with forward/backward navigation, consistent ordering, and link headers.
Best for: REST API pagination
API Versioning Strategy
Implement API versioning with URL path, header-based, and content negotiation strategies.
Best for: API backward compatibility
Debug with Inspector Protocol
Programmatic debugging with Node.js inspector module for heap snapshots, CPU profiling, and breakpoints.
Best for: Production performance profiling
ESM and CJS Module Interop
Handle ECMAScript module and CommonJS interop with dynamic imports, conditional exports, and dual packages.
Best for: Library dual packaging
Application Metrics Collection
Collect and expose application metrics like request counts, latency histograms, and custom gauges.
Best for: Prometheus metrics endpoint
Pub/Sub Messaging Pattern
Implement publish/subscribe messaging with topics, filtered subscriptions, and message replay.
Best for: In-process event messaging
Request ID Tracing Middleware
Express middleware that generates or forwards X-Request-Id headers for distributed tracing.
Best for: Distributed tracing
ETag Caching Middleware
Express middleware that generates ETags and handles 304 Not Modified responses for bandwidth savings.
Best for: API caching
Circuit Breaker Pattern
Implements the circuit breaker pattern to prevent cascading failures when calling external services.
Best for: External API calls
IP Geolocation Middleware
Extracts client IP and attaches geolocation data to the request using a lightweight lookup.
Best for: Content localization
Response Compression Middleware
Native zlib-based middleware that gzip-compresses responses above a size threshold.
Best for: Reducing API payload size
Request Timeout Middleware
Express middleware that aborts requests exceeding a configurable time limit with 408 status.
Best for: Preventing hanging requests
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
Multipart Upload Stream Handler
Handles multipart file uploads with streaming to disk without buffering the entire file in memory.
Best for: Large file uploads
Graceful HTTP Server Shutdown
Production-ready server shutdown that drains active connections and closes resources cleanly.
Best for: Container deployments
Structured Request Logger Middleware
Express middleware that logs request/response details as structured JSON with timing information.
Best for: API monitoring
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
Environment Secrets Loader
Loads and validates required environment variables at startup and throws meaningful errors for missing ones.
Best for: Application bootstrap
Server-Sent Events Handler
Express route that implements SSE for real-time server-to-client push notifications.
Best for: Live notifications
In-Memory Response Cache
Simple TTL-based in-memory cache middleware for GET endpoints that serves cached responses.
Best for: Caching expensive queries
Idempotency Key Middleware
Prevents duplicate request processing by caching responses keyed by the Idempotency-Key header.
Best for: Payment processing
OpenAPI Request Validator
Validates incoming request body against a JSON schema derived from an OpenAPI spec.
Best for: API input validation
Webhook Signature Verification
Verifies HMAC-SHA256 webhook signatures to ensure payloads are from trusted sources.
Best for: GitHub webhook handlers
JSON Stream Parser
Parses large JSON arrays from a readable stream without loading the entire file into memory.
Best for: Processing large log files
Health, Readiness & Liveness Checks
Express routes implementing Kubernetes-style health, readiness, and liveness probe endpoints.
Best for: Kubernetes deployments
Sliding Window Rate Limiter
Implements sliding window rate limiting that distributes limits more evenly than fixed windows.
Best for: API rate limiting