Skip to main content

Overview

The xrequestedwith middleware validates the X-Requested-With header, commonly used to identify AJAX requests and prevent CSRF attacks. Use it when you need:
  • AJAX request validation
  • CSRF protection layer
  • Request origin verification

Installation

Quick Start

Configuration

Options

Examples

Basic Validation

Custom Value

Specific Methods

Detection Only

API Reference

Functions

Client Usage

Technical Details

Implementation Overview

The middleware performs header validation through the following process:
  1. Method Filtering: Checks if the request method is in the skip list (default: GET, HEAD, OPTIONS)
  2. Path Filtering: Checks if the request path is in the skip paths list
  3. Header Validation: Compares the X-Requested-With header value (case-insensitive) against the expected value
  4. Error Handling: Returns either a custom error handler response or a default 400 Bad Request

Internal Components

  • Skip Methods Map: Pre-built map of HTTP methods to skip (defaults to safe methods)
  • Skip Paths Map: Pre-built map of paths to exclude from validation
  • Case-Insensitive Comparison: Uses strings.EqualFold for header value matching
  • Default Value: “XMLHttpRequest” is used when no custom value is specified

Function Variants

Security Note

While X-Requested-With adds a layer of protection, it should not be the sole CSRF defense. Combine with:
  • CSRF tokens
  • SameSite cookies
  • Origin validation

Best Practices

  • Use as additional security layer
  • Combine with CSRF middleware
  • Don’t rely on it alone
  • Document header requirement for clients

Testing

The middleware includes comprehensive test coverage for various scenarios:
  • csrf - CSRF protection
  • cors - CORS handling
  • bot - Bot detection