finalhandler is a Node.js utility function designed to standardize the final steps of an HTTP request within a server or middleware chain. It gracefully handles both successful completion (responding with a 404 for unhandled requests) and error scenarios, ensuring that the `ServerResponse` object is properly concluded and the `IncomingMessage` stream is unpiped. Currently at version 2.1.1, the library maintains an active development and maintenance cadence, with recent updates in both its v1 and v2 major versions. Its primary differentiation lies in providing a low-level, unopinionated mechanism for robust error and 404 response handling, including options for custom error logging, making it a foundational component for web frameworks like Express and Connect.
npm install finalhandlerVerified import paths — ran on the pinned version, not inferred.
Demonstrates how to use `finalhandler` to set up a basic HTTP server that serves a file, logging any errors to the console using the `onerror` option, and responding with appropriate HTTP status codes.
Upgrade Node.js to version 18.0.0 or higher, or explicitly lock `finalhandler` to a 1.x version in your `package.json`.
Review existing HTTP response headers in your application if upgrading from versions prior to 1.2.0 to ensure desired headers are explicitly set where necessary, particularly for error responses.
During development, ensure `NODE_ENV=development` to see stack traces. In production, utilize the `onerror` option to log detailed error information to a secure logging system, rather than exposing it to clients.
Ensure `finalhandler` is called as early as possible in the error handling chain, or use a conditional check like `if (!res.headersSent) { res.statusCode = ... }` before modifying headers if `finalhandler` is only one part of a more complex error handling strategy.In ES Modules, use `import finalhandler from 'finalhandler'` for loading. If you require `require()` functionality within an ESM file for other CJS modules, you can use `import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);`.Review your middleware chain and error handling logic. Ensure that `finalhandler` is called exclusively when no other response has been sent, or that preceding middleware correctly passes errors down the chain without prematurely sending a response. Check `res.headersSent` before attempting to modify headers.
This is expected behavior in production. For debugging, ensure `NODE_ENV=development` or `options.env` is not 'production'. For production error visibility, implement custom error logging using the `onerror` option to send stack traces to an internal logging service instead of exposing them to clients.
No dependency data recorded yet.