Debug Error Middleware

raw JSON →
1.3.0 verified Thu Apr 23 auth: no javascript abandoned

debug-error-middleware, currently at version 1.3.0 (last published 7 years ago), provides a development-focused error handling middleware for Express and Koa applications. Its primary function is to display detailed context information, including stack traces and object internals, in the response to failed requests. This is invaluable for debugging during development, offering insights into errors that would typically be suppressed or logged without immediate feedback to the client. A key differentiator is its automatic source map support, making transpiled code errors easier to interpret, though this can be disabled. The package's most critical aspect is its explicit and enforced prevention of use in production environments, as it leaks sensitive system information, making it solely a development utility. Given its last update date, the project appears to be abandoned.

error Error: debug-error-middleware cannot be loaded when NODE_ENV is 'production'
cause The middleware was initialized in an environment where `process.env.NODE_ENV` was set to 'production'. This is a built-in security measure.
fix
Ensure process.env.NODE_ENV is set to 'development' (or is unset) when running your application locally or in a development environment. Do not deploy this middleware to production.
error TypeError: Cannot read properties of undefined (reading 'express')
cause Attempting to `require` or `import` the module without specifying the `express` or `koa` named export, or using an incorrect import style for CommonJS modules.
fix
Use CommonJS named export destructuring: const { express: debugMiddleware } = require('debug-error-middleware'); or for Koa: const { koa: debugMiddleware } = require('debug-error-middleware'); if not using ESM-aware bundlers.
error Error: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: X)
cause Errors are not being caught by `debug-error-middleware`. This often happens if the middleware is placed *after* other routes or middleware that throw errors, or if asynchronous errors in Koa are not properly propagated.
fix
Ensure debug-error-middleware is applied as one of the very first middleware functions in your application stack. For Koa, explicit try/catch blocks around await next() within your error middleware can ensure proper error propagation for async operations.
breaking Enabling `debug-error-middleware` in a production environment is a severe security risk. It explicitly exposes sensitive information, including environment variables, stack traces, and internal object details, which attackers could exploit.
fix Ensure the middleware is conditionally loaded based on `NODE_ENV`. The library itself throws an error if `NODE_ENV` is 'production' when it's initialized. Always guard its usage with `if (process.env.NODE_ENV !== 'production') { app.use(debugMiddleware()); }`.
gotcha The middleware must be loaded as one of the *first* middlewares in your application's chain (especially for Express) to ensure it can catch errors from all subsequent middleware and routes. Incorrect placement may result in errors being handled by default Express/Koa handlers or other middlewares.
fix For Express, `app.use(debugMiddleware());` should be called before any routes or other middleware that could potentially throw errors. For Koa, ensure it's wrapped in a `try/catch` block within an `app.use` that is added early in the middleware stack.
breaking The library explicitly checks `process.env.NODE_ENV`. If it's set to 'production', the middleware will deliberately throw an error during initialization, preventing accidental deployment in an unsafe configuration.
fix Always set `NODE_ENV` correctly for your deployment environment. For development, `NODE_ENV=development` or unset, and for production, `NODE_ENV=production`.
gotcha The project appears to be abandoned, with no updates in 7 years. While functional, it may not receive patches for future security vulnerabilities, compatibility issues with newer Node.js versions, or updates for newer Express/Koa features or paradigms (e.g., ESM).
fix For new projects, consider actively maintained alternatives like `errorhandler` for Express, which also provides similar debug-focused error handling, or robust custom error-handling middleware patterns tailored for production.
npm install debug-error-middleware
yarn add debug-error-middleware
pnpm add debug-error-middleware

This quickstart demonstrates how to integrate `debug-error-middleware` into an Express application, ensuring it's only active in development and correctly positioned to catch errors.

import express from 'express';
import { express as debugMiddleware } from 'debug-error-middleware';

const app = express();

// CRITICAL: ONLY enable in development!
if (process.env.NODE_ENV === 'development' || !process.env.NODE_ENV) {
  // The debug middleware should be loaded first to catch errors from all other middleware.
  app.use(debugMiddleware({
    theme: 'okaidia', // Optional: customize Prism.js theme
    disabledForXHR: true // Optional: disable for XHR requests
  }));
}

// Simulate an API route that throws an error
app.get('/error', (req, res, next) => {
  const customError = new Error('Something went wrong during data processing.');
  customError.statusCode = 400;
  customError.data = { requestBody: req.body, queryParams: req.query };
  next(customError);
});

// A catch-all for routes not found, which will also trigger the error handler
app.use((req, res, next) => {
  const notFoundError = new Error(`Cannot ${req.method} ${req.originalUrl}`);
  notFoundError.statusCode = 404;
  next(notFoundError);
});

// Start the server
const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`Server running on http://localhost:${port} in ${process.env.NODE_ENV || 'development'} mode`);
  console.log('Access /error to see the debug output in development.');
});