Install finalhandler via npm
masterInstall the finalhandler module using the npm registry:
$ npm install finalhandlerrepository·master·Indexed 42 days ago
https://github.com/pillarjs/finalhandlerA Node.js utility used as the final step in an HTTP request lifecycle to respond to requests, handle 404s, and manage error responses gracefully. Version 2.1.1 provides configurable environment settings to prevent leaking error stacks in production and an optional onerror callback for centralized logging.
Install the finalhandler module using the npm registry:
$ npm install finalhandlerWhen calling finalhandler(req, res, options), you can provide the following configuration keys:
options.env: Determines the environment. Defaults to the value of the NODE_ENV environment variable. Use 'production' to ensure error stacks are not leaked in the response body.options.onerror: A function called when an error occurs. This is useful for centralized logging. The function is called with the signature onerror(err, req, res).Use the returned handler to catch errors during asynchronous operations like reading files.
const finalhandler = require('finalhandler')
const fs = require('fs')
const http = require('http')
const server = http.createServer((req, res) => {
const done = finalhandler(req, res)
fs.readFile('index.html', (err, buf) => {
if (err) return done(err)
res.setHeader('Content-Type', 'text/html')
res.end(buf)
})
})
server.listen(3000)Use the onerror option to intercept errors for logging purposes without generating new functions on every request.
const finalhandler = require('finalhandler')
const fs = require('fs')
const http = require('http')
const server = http.createServer((req, res) => {
const done = finalhandler(req, res, { onerror: logerror })
fs.readFile('index.html', (err, buf) => {
if (err) return done(err)
res.setHeader('Content-Type', 'text/html')
res.end(buf)
})
})
server.listen(3000)
function logerror (err) {
console.error(err.stack || err.toString())
}Pass the finalhandler instance as the next callback to middleware functions (like serve-static) to ensure they can signal the end of the request chain.
const finalhandler = require('finalhandler')
const http = require('http')
const serveStatic = require('serve-static')
const serve = serveStatic('public')
const server = http.createServer((req, res) => {
const done = finalhandler(req, res)
serve(req, res, done)
})
server.listen(3000)If you want to ensure every request that reaches the end of your logic results in a 404, invoke the handler without an error.
const finalhandler = require('finalhandler')
const http = require('http')
const server = http.createServer((req, res) => {
const done = finalhandler(req, res)
done()
})
server.listen(3000)The finalhandler function returns a function that should be invoked as the final step of an HTTP request lifecycle. This returned function is called as fn(err).
err is falsy: The handler writes a 404 response to the res object.err is truthy: An error response is written to res. If a response has already started, res will be terminated.Error Response Behavior:
res.statusCode: Set from err.status or err.statusCode. If the value is not in the 4xx or 5xx range, it defaults to 500.res.statusMessage: Set according to the status code.options.env is 'production', the body is the HTML of the status code message. Otherwise, the body contains err.stack.err.headers object are applied.Side Effects:
The handler will unpipe anything from req when it is invoked.
const finalhandler = require('finalhandler')
// Returns a function 'done'
const done = finalhandler(req, res, options)
// Invoke it as the final step
done(err)The finalhandler function creates a handler for the final step of an HTTP response. It is typically used in middleware stacks to catch unhandled errors or to provide a default 404 response when no other middleware handles the request.
err.status or err.statusCode) and headers (err.headers). If no valid status is found, it falls back to the response's current status code (defaulting to 500 if invalid). In non-production environments, the error stack is sent as the response body.404 Not Found response with a message indicating the method and resource (e.g., Cannot GET /path).env: The environment string (e.g., 'production'). If not set, it defaults to process.env.NODE_ENV or 'development'. In non-production environments, error stacks are included in the response body.onerror: A callback function invoked when an error is handled. It is called with (err, req, res) using setImmediate.const finalhandler = require('finalhandler')
const http = require('http')
const server = http.createServer((req, res) => {
// Create the handler
const done = finalhandler(req, res, {
onerror: (err, req, res) => {
console.error('Unhandled error:', err)
}
})
// Example usage in a middleware-like pattern
// If an error occurs, pass it to 'done'
// If no error occurs, call 'done()' to trigger a 404
done(new Error('Something went wrong'))
})
server.listen(3000)You can provide an onerror function in the options object passed to finalhandler. This callback is executed asynchronously via setImmediate whenever an error is passed to the handler. This is useful for logging errors to external services or internal monitoring tools without blocking the response flow.
The callback signature is (err, req, res).
const handler = finalhandler(req, res, {
onerror: (err, req, res) => {
// Log error to your monitoring service
myLogger.error(err, { url: req.url })
}
})
// Trigger the error handler
handler(new Error('Database connection failed'))