Package detail

finalhandler

pillarjs181.2mMIT2.1.0

Node.js final http responder

readme

finalhandler

NPM Version NPM Downloads Node.js Version Build Status Test Coverage

Node.js function to invoke as the final step to respond to HTTP request.

Installation

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install finalhandler

API

var finalhandler = require('finalhandler')

finalhandler(req, res, [options])

Returns function to be invoked as the final step for the given req and res. This function is to be invoked as fn(err). If err is falsy, the handler will write out a 404 response to the res. If it is truthy, an error response will be written out to the res or res will be terminated if a response has already started.

When an error is written, the following information is added to the response:

  • The res.statusCode is set from err.status (or err.statusCode). If this value is outside the 4xx or 5xx range, it will be set to 500.
  • The res.statusMessage is set according to the status code.
  • The body will be the HTML of the status code message if env is 'production', otherwise will be err.stack.
  • Any headers specified in an err.headers object.

The final handler will also unpipe anything from req when it is invoked.

options.env

By default, the environment is determined by NODE_ENV variable, but it can be overridden by this option.

options.onerror

Provide a function to be called with the err when it exists. Can be used for writing errors to a central location without excessive function generation. Called as onerror(err, req, res).

Examples

always 404

var finalhandler = require('finalhandler')
var http = require('http')

var server = http.createServer(function (req, res) {
  var done = finalhandler(req, res)
  done()
})

server.listen(3000)

perform simple action

var finalhandler = require('finalhandler')
var fs = require('fs')
var http = require('http')

var server = http.createServer(function (req, res) {
  var done = finalhandler(req, res)

  fs.readFile('index.html', function (err, buf) {
    if (err) return done(err)
    res.setHeader('Content-Type', 'text/html')
    res.end(buf)
  })
})

server.listen(3000)

use with middleware-style functions

var finalhandler = require('finalhandler')
var http = require('http')
var serveStatic = require('serve-static')

var serve = serveStatic('public')

var server = http.createServer(function (req, res) {
  var done = finalhandler(req, res)
  serve(req, res, done)
})

server.listen(3000)

keep log of all errors

var finalhandler = require('finalhandler')
var fs = require('fs')
var http = require('http')

var server = http.createServer(function (req, res) {
  var done = finalhandler(req, res, { onerror: logerror })

  fs.readFile('index.html', function (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())
}

License

MIT

changelog

v2.1.0 / 2025-03-05

  • deps:
    • use caret notation for dependency versions
    • encodeurl@^2.0.0
    • debug@^4.4.0
  • remove ServerResponse.headersSent support check
  • remove setImmediate support check
  • update test dependencies
  • remove unnecessary devDependency safe-buffer
  • remove unpipe package and use native unpipe() method
  • remove unnecessary devDependency readable-stream
  • refactor: use object spread to copy error headers
  • refactor: use replaceAll instead of replace with a regex
  • refactor: replace setHeaders function with optimized inline header setting

v2.0.0 / 2024-09-02

  • drop support for node <18
  • ignore status message for HTTP/2 (#53)

v1.3.1 / 2024-09-11

  • deps: encodeurl@~2.0.0

v1.3.0 / 2024-09-03

  • ignore status message for HTTP/2 (#53)

v1.2.1 / 2024-09-02

  • Gracefully handle when handling an error and socket is null

1.2.0 / 2022-03-22

  • Remove set content headers that break response
  • deps: on-finished@2.4.1
  • deps: statuses@2.0.1
    • Rename 425 Unordered Collection to standard 425 Too Early

1.1.2 / 2019-05-09

  • Set stricter Content-Security-Policy header
  • deps: parseurl@~1.3.3
  • deps: statuses@~1.5.0

1.1.1 / 2018-03-06

  • Fix 404 output for bad / missing pathnames
  • deps: encodeurl@~1.0.2
    • Fix encoding % as last character
  • deps: statuses@~1.4.0

1.1.0 / 2017-09-24

  • Use res.headersSent when available

1.0.6 / 2017-09-22

  • deps: debug@2.6.9

1.0.5 / 2017-09-15

  • deps: parseurl@~1.3.2
    • perf: reduce overhead for full URLs
    • perf: unroll the "fast-path" RegExp

1.0.4 / 2017-08-03

  • deps: debug@2.6.8

1.0.3 / 2017-05-16

  • deps: debug@2.6.7
    • deps: ms@2.0.0

1.0.2 / 2017-04-22

  • deps: debug@2.6.4
    • deps: ms@0.7.3

1.0.1 / 2017-03-21

  • Fix missing </html> in HTML document
  • deps: debug@2.6.3
    • Fix: DEBUG_MAX_ARRAY_LENGTH

1.0.0 / 2017-02-15

  • Fix exception when err cannot be converted to a string
  • Fully URL-encode the pathname in the 404 message
  • Only include the pathname in the 404 message
  • Send complete HTML document
  • Set Content-Security-Policy: default-src 'self' header
  • deps: debug@2.6.1
    • Allow colors in workers
    • Deprecated DEBUG_FD environment variable set to 3 or higher
    • Fix error when running under React Native
    • Use same color for same namespace
    • deps: ms@0.7.2

0.5.1 / 2016-11-12

  • Fix exception when err.headers is not an object
  • deps: statuses@~1.3.1
  • perf: hoist regular expressions
  • perf: remove duplicate validation path

0.5.0 / 2016-06-15

  • Change invalid or non-numeric status code to 500
  • Overwrite status message to match set status code
  • Prefer err.statusCode if err.status is invalid
  • Set response headers from err.headers object
  • Use statuses instead of http module for status messages
    • Includes all defined status messages

0.4.1 / 2015-12-02

  • deps: escape-html@~1.0.3
    • perf: enable strict mode
    • perf: optimize string replacement
    • perf: use faster string coercion

0.4.0 / 2015-06-14

  • Fix a false-positive when unpiping in Node.js 0.8
  • Support statusCode property on Error objects
  • Use unpipe module for unpiping requests
  • deps: escape-html@1.0.2
  • deps: on-finished@~2.3.0
    • Add defined behavior for HTTP CONNECT requests
    • Add defined behavior for HTTP Upgrade requests
    • deps: ee-first@1.1.1
  • perf: enable strict mode
  • perf: remove argument reassignment

0.3.6 / 2015-05-11

  • deps: debug@~2.2.0
    • deps: ms@0.7.1

0.3.5 / 2015-04-22

  • deps: on-finished@~2.2.1
    • Fix isFinished(req) when data buffered

0.3.4 / 2015-03-15

  • deps: debug@~2.1.3
    • Fix high intensity foreground color for bold
    • deps: ms@0.7.0

0.3.3 / 2015-01-01

  • deps: debug@~2.1.1
  • deps: on-finished@~2.2.0

0.3.2 / 2014-10-22

  • deps: on-finished@~2.1.1
    • Fix handling of pipelined requests

0.3.1 / 2014-10-16

  • deps: debug@~2.1.0
    • Implement DEBUG_FD env variable support

0.3.0 / 2014-09-17

  • Terminate in progress response only on error
  • Use on-finished to determine request status

0.2.0 / 2014-09-03

  • Set X-Content-Type-Options: nosniff header
  • deps: debug@~2.0.0

0.1.0 / 2014-07-16

  • Respond after request fully read
    • prevents hung responses and socket hang ups
  • deps: debug@1.0.4

0.0.3 / 2014-07-11

  • deps: debug@1.0.3
    • Add support for multiple wildcards in namespaces

0.0.2 / 2014-06-19

  • Handle invalid status codes

0.0.1 / 2014-06-05

  • deps: debug@1.0.2

0.0.0 / 2014-06-05

  • Extracted from connect/express