or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

configuration.mdfile-system.mdindex.mdrequest-handling.md
tile.json

tessl/npm-serve-handler

HTTP request routing and static file serving library that powers the serve package

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/serve-handler@6.1.x

To install, run

npx @tessl/cli install tessl/npm-serve-handler@6.1.0

index.mddocs/

Serve Handler

Serve Handler is the routing foundation of the serve package, providing comprehensive HTTP request routing and static file serving capabilities. It offers extensive configuration options for URL rewriting, redirects, clean URLs, custom headers, directory listing, and middleware integration.

Package Information

  • Package Name: serve-handler
  • Package Type: npm
  • Language: JavaScript (Node.js)
  • Installation: npm install serve-handler

Core Imports

const handler = require('serve-handler');

For ESM:

import handler from 'serve-handler';

Basic Usage

const handler = require('serve-handler');
const http = require('http');

const server = http.createServer(async (request, response) => {
  // Serve files from current directory
  await handler(request, response);
});

server.listen(3000);

With configuration:

const handler = require('serve-handler');
const micro = require('micro');

module.exports = micro(async (request, response) => {
  await handler(request, response, {
    public: './public',
    cleanUrls: true,
    trailingSlash: false
  });
});

Architecture

Serve Handler is built around several key components:

  • Main Handler: Core async function that processes HTTP requests and responses
  • Path Resolution: Intelligent path matching with support for rewrites, redirects, and clean URLs
  • File System Abstraction: Pluggable file system operations for custom storage backends
  • Template System: Built-in HTML templates for directory listings and error pages
  • Security Layer: Path traversal protection and symlink handling
  • HTTP Features: Range requests, ETag caching, custom headers, and content negotiation

Capabilities

Request Handler

Core HTTP request and response processing with extensive configuration options for static file serving, routing, and response customization.

/**
 * Main HTTP request handler for routing and static file serving
 * @param request - HTTP request object
 * @param response - HTTP response object  
 * @param config - Configuration options object
 * @param methods - Custom file system method overrides
 * @returns Promise that resolves when request handling is complete
 */
async function handler(
  request: IncomingMessage,
  response: ServerResponse,
  config?: Config,
  methods?: Methods
): Promise<void>;

Request Handling

Configuration Options

Comprehensive configuration system supporting URL rewrites, redirects, clean URLs, custom headers, directory listing controls, and advanced routing patterns.

interface Config {
  /** Directory path to serve files from */
  public?: string;
  /** Enable clean URLs by stripping .html extensions */
  cleanUrls?: boolean | string[];
  /** URL rewrite rules */
  rewrites?: RewriteRule[];
  /** URL redirect rules */  
  redirects?: RedirectRule[];
  /** Custom header rules */
  headers?: HeaderRule[];
  /** Enable/configure directory listing */
  directoryListing?: boolean | string[];
  /** Files/patterns to exclude from directory listings */
  unlisted?: string[];
  /** Force trailing slash behavior on URLs */
  trailingSlash?: boolean;
  /** Render single file in directory instead of listing */
  renderSingle?: boolean;
  /** Follow symbolic links */
  symlinks?: boolean;
  /** Use ETag headers instead of Last-Modified */
  etag?: boolean;
}

Configuration

File System Methods

Pluggable file system abstraction allowing custom implementations for different storage backends, cloud storage, or specialized file handling requirements.

interface Methods {
  /** Custom lstat implementation */
  lstat?: (path: string, fromDir?: boolean) => Promise<Stats>;
  /** Custom realpath implementation */
  realpath?: (path: string) => Promise<string>;
  /** Custom read stream creator */
  createReadStream?: (path: string, options?: object) => ReadableStream;
  /** Custom directory reader */
  readdir?: (path: string) => Promise<string[]>;
  /** Custom error handler */
  sendError?: (absolutePath: string, response: ServerResponse, acceptsJSON: boolean, current: string, handlers: object, config: Config, spec: ErrorSpec) => Promise<void>;
}

File System Integration

Types

interface RewriteRule {
  /** Source pattern (glob/regex) */
  source: string;
  /** Target path or URL */
  destination: string;
}

interface RedirectRule {
  /** Source pattern (glob/regex) */
  source: string;
  /** Target path or URL */
  destination: string;
  /** HTTP status code (default: 301) */
  type?: number;
}

interface HeaderRule {
  /** Source pattern (glob/regex) */
  source: string;
  /** Headers to apply */
  headers: Array<{
    key: string;
    value: string;
  }>;
}

interface ErrorSpec {
  /** HTTP status code */
  statusCode: number;
  /** Error code identifier */
  code: string;
  /** Error message */
  message: string;
  /** Original error object (optional) */
  err?: Error;
}