@prexjs/finalhandler
v1.0.0
Published
Node.js final step HTTP responder invoked when no middleware responds or when an unhandled error occurs.
Readme
@prexjs/finalhandler
Node.js final step HTTP responder invoked when no middleware responds or when an unhandled error occurs.
@prexjs/finalhandler provides a standard termination function for Node.js HTTP servers and middleware pipelines. It is invoked as the last step in a request lifecycle when no route handler writes a response or when an unhandled error occurs, ensuring the connection is always cleanly closed with an appropriate HTTP status code (such as 404 Not Found or 500 Internal Server Error).
Features
- 404 Not Found Default: Gracefully sends a 404 response when the request pipeline runs without sending headers or writing a body.
- Error Formatting: Formats error messages safely based on environment (e.g. hiding stack traces in production).
- Header Management: Resets invalid or broken response headers before sending error status payloads.
- Lifecycle Integration: Works seamlessly with
@prexjs/finishedto ensure streams and sockets are not orphaned. - TypeScript Support: Complete type definitions for ESM and CommonJS environments.
Installation
Install using your preferred package manager:
# npm
npm install @prexjs/finalhandler
# pnpm
pnpm add @prexjs/finalhandler
# Yarn
yarn add @prexjs/finalhandler
# Bun
bun add @prexjs/finalhandlerQuick start
import http from 'node:http';
import finalhandler from '@prexjs/finalhandler';
const server = http.createServer((req, res) => {
const done = finalhandler(req, res, {
env: process.env.NODE_ENV || 'development',
onerror: (err) => {
console.error('Request pipeline error:', err);
},
});
// If no middleware handles the route, invoke done()
if (req.url === '/ping') {
res.end('pong');
} else {
done(); // Sends 404 Not Found
}
});
server.listen(3000);Compatibility
- Node.js >= 18.0.0
- Supports both ESM and CommonJS
- TypeScript 5.0+
Related Packages
@prexjs/prex: The core Prex web framework.@prexjs/finished: Stream and message completion tracking.@prexjs/http-errors: HTTP error generation.
