Build Production-Grade Node.js Express Middleware with Logging and Auth

Create configurable Express middleware with structured logging, custom error classes, performance metrics, and comprehensive tests.

๐Ÿ“ The Prompt

Write a production-grade Express.js middleware in [JAVASCRIPT_OR_TYPESCRIPT] that handles [MIDDLEWARE_PURPOSE] for a [APPLICATION_TYPE] application. **Core Behavior:** The middleware should intercept [REQUEST_TYPES] requests and perform the following: 1. [PRIMARY_ACTION] โ€” describe the main logic (e.g., verify JWT tokens, transform request body, enforce rate limits) 2. Attach processed data to `req.[CUSTOM_PROPERTY]` for downstream route handlers 3. Call `next()` on success or `next(error)` on failure with appropriate HTTP status codes **Implementation Requirements:** 1. **Configuration**: Export a factory function that accepts an options object: `{ [CONFIG_PARAMS] }`. This allows different routes to use the middleware with different settings. 2. **Error Handling**: Create a custom error class `[ERROR_CLASS_NAME]` extending `Error` with `statusCode`, `code`, and `details` properties. Throw structured errors that a centralized error handler can process. 3. **Logging**: Integrate structured logging using [LOGGING_LIBRARY] (e.g., winston, pino). Log middleware entry, decision outcomes, and errors with correlation IDs from `req.headers['x-request-id']`. 4. **Performance**: Add timing metrics using `process.hrtime.bigint()` and log middleware execution duration. Skip processing for [EXCLUDED_ROUTES] using path matching. 5. **Testing**: Write 4 test cases using [TEST_FRAMEWORK]: successful pass-through, authentication failure, malformed input, and skipped route. Include the middleware file, the custom error class, and the test file. Add inline comments for non-obvious decisions.

๐Ÿ’ก Tips for Better Results

Use the factory function pattern (middleware that returns middleware) โ€” specify your config params clearly for the best result. Always include a custom error class to avoid losing error context in production. Request path-exclusion logic upfront so health-check and public routes aren't blocked.

๐ŸŽฏ Use Cases

Node.js backend engineers use this when building middleware layers for authentication, request validation, or request enrichment in Express-based APIs.

๐Ÿ”— Related Prompts

๐Ÿ’ป Coding beginner

Explain Code Like Im a Beginner

Get any code explained in plain English with line-by-line breakdowns, analogies, and learning suggestions.

๐Ÿ’ป Coding beginner

Debug My Code and Explain the Fix

Get your code debugged with clear explanations of what went wrong and why, plus the corrected version.

๐Ÿ’ป Coding intermediate

Write Unit Tests for My Code

Generate thorough unit tests covering edge cases, error handling, and both positive and negative scenarios.

๐Ÿ’ป Coding intermediate

Convert Code Between Languages

Convert code between any programming languages while maintaining idiomatic patterns and best practices.

๐Ÿ’ป Coding intermediate

Write a REST API Endpoint

Generate production-ready REST API endpoints with validation, error handling, and documentation.

๐Ÿ’ป Coding advanced

Create a GitHub Actions CI/CD Workflow for Automated Testing and Deployment

Generate a complete GitHub Actions CI/CD workflow with build, test, deploy, and notification jobs for your project.