finalhandler is a Node.js function that serves as the final step in HTTP request handling chains. It provides standardized error handling and 404 responses for HTTP servers and middleware stacks, with automatic status code resolution, security headers, and environment-based error reporting.
npm install finalhandlerconst finalhandler = require('finalhandler');const finalhandler = require('finalhandler');
const http = require('http');
const server = http.createServer(function (req, res) {
const done = finalhandler(req, res);
// Handle request - if no response is sent, this will send 404
done();
});
server.listen(3000);finalhandler implements a standardized HTTP error handling pipeline with several key components:
finalhandler() function creates customized handler functions that capture request/response context and configurationerr.status or err.statusCode), validates ranges (400-599), and falls back to response status or 500req.unpipe() and onFinished() to handle incomplete or aborted requestsres.headersSent to determine if response has started, destroying sockets if necessary to prevent hanging connectionsCreates a function to invoke as the final step in HTTP request processing. Handles both error responses and 404 cases with proper status codes, headers, and HTML output.
/**
* Create a function to handle the final response
* @param {IncomingMessage} req - HTTP request object
* @param {OutgoingMessage} res - HTTP response object
* @param {Object} [options] - Configuration options
* @returns {Function} Handler function that accepts an error parameter
*/
function finalhandler(req, res, options);Usage Examples:
const finalhandler = require('finalhandler');
const fs = require('fs');
const http = require('http');
// Basic error handling
const server = http.createServer(function (req, res) {
const done = finalhandler(req, res);
fs.readFile('index.html', function (err, buf) {
if (err) return done(err); // Will send appropriate error response
res.setHeader('Content-Type', 'text/html');
res.end(buf);
});
});
// With custom error logging
const server2 = http.createServer(function (req, res) {
const done = finalhandler(req, res, {
onerror: function(err, req, res) {
console.error('Error occurred:', err.stack);
}
});
// Request handling logic...
done(); // Will send 404 if no response was sent
});
// With middleware-style functions
const serveStatic = require('serve-static');
const serve = serveStatic('public');
const server3 = http.createServer(function (req, res) {
const done = finalhandler(req, res);
serve(req, res, done); // done will be called if serve-static doesn't handle the request
});The function returned by finalhandler() processes errors and sends appropriate HTTP responses.
/**
* Handler function that processes errors and sends HTTP responses
* @param {Error} [err] - Error object to handle, or falsy for 404 response
*/
function handler(err);When called with an error:
res.statusCode from err.status or err.statusCode (400-599 range)err.headers object if presentoptions.onerror callback if providedWhen called without error:
/**
* Configuration options for finalhandler
*/
interface Options {
/** Environment setting (defaults to NODE_ENV or 'development') */
env?: string;
/** Error callback function called when errors occur */
onerror?: (err: Error, req: IncomingMessage, res: OutgoingMessage) => void;
}
/**
* Error objects with optional HTTP properties
*/
interface HttpError extends Error {
/** HTTP status code (400-599) */
status?: number;
/** Alternative status code property */
statusCode?: number;
/** Additional headers to include in response */
headers?: Record<string, string>;
}The handler automatically:
err.status or err.statusCode if in 400-599 range, otherwise falls back to response status or 500err.headers properties in the response when error has valid statusDevelopment Mode (default):
options.env is not 'production'Production Mode:
options.env is 'production'finalhandler is designed for: