Skip to main content

Overview

The filter middleware provides request filtering capabilities, allowing or blocking requests based on custom conditions. Use it when you need:
  • Block specific requests
  • Conditional access
  • Request validation

Installation

Quick Start

Configuration

Options

Examples

Allow Function

Block by User-Agent

Custom Error

Combine Conditions

API Reference

Functions

Technical Details

The filter middleware provides comprehensive request filtering through multiple criteria:

Pattern Matching

The middleware uses glob-to-regex conversion for flexible pattern matching:
  • * - Matches any characters except path separators (e.g., /api/* matches /api/users but not /api/users/1)
  • ** - Matches any characters including path separators (e.g., /admin/** matches /admin/deep/nested/path)
  • ? - Matches exactly one character
Special regex characters (., +, ^, $, |, etc.) are automatically escaped.

Filter Evaluation Order

Filters are evaluated in the following order:
  1. HTTP Methods - Check if method is in AllowedMethods (if configured)
  2. Blocked Hosts - Check if host is in BlockedHosts (takes precedence over allowed)
  3. Allowed Hosts - Check if host is in AllowedHosts (if configured)
  4. Blocked Paths - Check if path matches BlockedPaths patterns (takes precedence over allowed)
  5. Allowed Paths - Check if path matches AllowedPaths patterns (if configured)
  6. Blocked User Agents - Check if UA matches BlockedUserAgents patterns (takes precedence over allowed)
  7. Allowed User Agents - Check if UA matches AllowedUserAgents patterns (if configured)
  8. Custom Filter - Execute CustomFilter function if provided
If any check fails, the request is blocked and the OnBlock handler is called (or returns 403 Forbidden by default).

Host Normalization

Host names are normalized by:
  • Converting to lowercase for case-insensitive matching
  • Stripping port numbers (e.g., example.com:8080 becomes example.com)

Performance Optimization

  • HTTP methods are stored in a map for O(1) lookup
  • Hosts are stored in maps for O(1) lookup
  • Glob patterns are compiled to regex once during initialization
  • All patterns are pre-compiled to avoid runtime compilation overhead

Best Practices

  • Keep filter logic simple
  • Log blocked requests
  • Use descriptive error messages
  • Combine with rate limiting

Testing

The filter middleware includes comprehensive test coverage for all filtering scenarios: