CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-serve-handler

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

Pending
Overview
Eval results
Files

request-handling.mddocs/

Request Handling

Core HTTP request and response processing functionality that routes requests, resolves file paths, handles directory listings, serves static files, and manages error responses.

Capabilities

Main Handler Function

Processes incoming HTTP requests and generates appropriate responses, handling static file serving, directory listings, redirects, and error conditions.

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

Usage Examples:

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

// Basic static file server
const server = http.createServer(async (req, res) => {
  await handler(req, res);
});

// With custom configuration
const server = http.createServer(async (req, res) => {
  await handler(req, res, {
    public: './dist',
    cleanUrls: true,
    headers: [{
      source: '**/*.js',
      headers: [{
        key: 'Cache-Control',
        value: 'max-age=31536000'
      }]
    }]
  });
});

// With custom file system methods
const server = http.createServer(async (req, res) => {
  await handler(req, res, {}, {
    lstat: async (path) => {
      // Custom stat implementation
      return await customLstat(path);
    },
    createReadStream: (path, options) => {
      // Custom read stream (e.g., from cloud storage)
      return customReadStream(path, options);
    }
  });
});

Request Processing Flow

The handler processes requests through the following stages:

  1. URL Parsing: Decodes the request URL and validates it
  2. Path Resolution: Resolves the file system path and checks for path traversal
  3. Redirect Handling: Applies clean URL, trailing slash, and custom redirect rules
  4. File Resolution: Attempts to locate the requested file, including clean URL fallbacks
  5. Directory Handling: Renders directory listings or serves single files from directories
  6. File Serving: Streams file content with appropriate headers and range support
  7. Error Handling: Generates error responses for missing files or server errors

Response Types

The handler can generate several types of responses:

  • Static Files: Direct file serving with proper MIME types and caching headers
  • Directory Listings: HTML or JSON directory listings with navigation
  • Redirects: 301/302 redirects for clean URLs, trailing slashes, or custom rules
  • Error Pages: 404, 500, and other HTTP error responses with custom error pages
  • Range Responses: Partial content responses (206) for range requests

Content Negotiation

The handler supports content negotiation based on request headers:

  • Accept Header: Detects JSON preference for directory listings
  • Range Header: Handles partial content requests for large files
  • If-None-Match: Supports conditional requests with ETag headers

Security Features

Built-in security protections:

  • Path Traversal Protection: Prevents access to files outside the public directory
  • Symlink Control: Configurable symlink following to prevent security issues
  • File Exclusion: Automatic exclusion of sensitive files (.git, .DS_Store, etc.)

Error Handling

Comprehensive error handling with custom error page support:

// Custom error handling
const server = http.createServer(async (req, res) => {
  await handler(req, res, {}, {
    sendError: async (absolutePath, response, acceptsJSON, current, handlers, config, spec) => {
      // Custom error response logic
      if (spec.statusCode === 404) {
        response.statusCode = 404;
        response.setHeader('Content-Type', 'text/html');
        response.end('<h1>Custom 404 Page</h1>');
      } else {
        // Fallback to default error handling
        await handlers.sendError(absolutePath, response, acceptsJSON, current, handlers, config, spec);
      }
    }
  });
});

Install with Tessl CLI

npx tessl i tessl/npm-serve-handler

docs

configuration.md

file-system.md

index.md

request-handling.md

tile.json