or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

finalhandler

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.

Package Information

  • Package Name: finalhandler
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install finalhandler

Core Imports

const finalhandler = require('finalhandler');

Basic Usage

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);

Architecture

finalhandler implements a standardized HTTP error handling pipeline with several key components:

  • Handler Factory Pattern: The main finalhandler() function creates customized handler functions that capture request/response context and configuration
  • Error Resolution Pipeline: Multi-step process that extracts status codes from error objects (err.status or err.statusCode), validates ranges (400-599), and falls back to response status or 500
  • Stream Management: Automatic cleanup of request streams using req.unpipe() and onFinished() to handle incomplete or aborted requests
  • Response State Handling: Checks res.headersSent to determine if response has started, destroying sockets if necessary to prevent hanging connections
  • Environment-Aware Output: Switches between detailed stack traces (development) and sanitized messages (production) based on environment configuration
  • Security Integration: Automatic injection of security headers (CSP, X-Content-Type-Options) and HTML escaping to prevent XSS attacks

Capabilities

Final Handler Creation

Creates 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
});

Handler Function

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:

  • Sets res.statusCode from err.status or err.statusCode (400-599 range)
  • Falls back to existing response status code or 500
  • Includes headers from err.headers object if present
  • Shows error stack in development, sanitized message in production
  • Calls options.onerror callback if provided

When called without error:

  • Sends 404 status with "Cannot METHOD /path" message
  • Uses encoded URL path in the message

Types

/**
 * 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>;
}

Error Handling Behavior

The handler automatically:

  • Status Code Resolution: Uses err.status or err.statusCode if in 400-599 range, otherwise falls back to response status or 500
  • Header Processing: Includes err.headers properties in the response when error has valid status
  • Message Generation: Shows full stack trace in development mode, sanitized status messages in production
  • Security Headers: Adds CSP and X-Content-Type-Options headers to prevent XSS
  • Request Cleanup: Unpipes request streams and handles response completion
  • Socket Management: Destroys socket if headers have already been sent

Environment Modes

Development Mode (default):

  • Shows complete error stack traces
  • Displays detailed error information
  • Activated when options.env is not 'production'

Production Mode:

  • Shows only sanitized HTTP status messages
  • Hides sensitive error details for security
  • Activated when options.env is 'production'

Integration Patterns

finalhandler is designed for:

  • HTTP Servers: As the final error handler in request processing
  • Middleware Frameworks: Compatible with Express.js, Connect, and similar frameworks
  • Error Boundaries: Provides consistent error handling across different server implementations
  • 404 Handling: Automatic not-found responses when no other handler processes the request

Security Features

  • HTML Escaping: All user-provided content is escaped to prevent XSS
  • Security Headers: Sets Content-Security-Policy and X-Content-Type-Options headers
  • Production Sanitization: Hides error details in production environments
  • Safe Stream Handling: Properly cleans up request streams and socket connections