Skip to main content

Overview

The forwarded middleware parses X-Forwarded-* headers set by load balancers and proxies, extracting client IP, protocol, host, and other forwarded information.

Installation

Quick Start

Configuration

Headers Parsed

Examples

Basic Usage

Trusted Proxies Only

Helper Functions

Info Struct

API Reference

Technical Details

Header Processing Priority

The middleware processes headers in the following order:
  1. X-Forwarded-For: Extracts the client IP from the first entry in the comma-separated list
  2. X-Forwarded-Host: Sets the original host requested by the client
  3. X-Forwarded-Proto: Determines if the original request was HTTP or HTTPS
  4. X-Forwarded-Port: Captures the original port number
  5. X-Forwarded-Prefix: Records any path prefix added by reverse proxies
  6. Forwarded (RFC 7239): Parses the standardized Forwarded header, which can override previous values

Trusted Proxy Validation

When TrustedProxies is configured:
  • IP addresses are automatically converted to CIDR notation (single IPs get /32)
  • The middleware checks if the remote address matches any trusted CIDR ranges
  • If no match is found, all X-Forwarded-* headers are ignored and the remote address is used

IP Parsing

The middleware handles various IP address formats:
  • Standard IPv4 addresses (e.g., 192.168.1.1)
  • IPv6 addresses in RFC 7239 format with brackets (e.g., [2001:db8::1])
  • Addresses with port numbers (automatically stripped)

Context Storage

Forwarded information is stored in the request context using a private context key, making it accessible throughout the request lifecycle via helper functions.

Best Practices

  1. Always specify trusted proxies in production environments to prevent header spoofing
  2. Use CIDR notation for trusted proxy ranges to cover entire subnets
  3. Validate client IPs after extraction if using them for security decisions
  4. Prefer RFC 7239 Forwarded header when possible for better standardization
  5. Disable TrustProxy when not behind a reverse proxy to avoid security issues

Testing

The middleware includes comprehensive test coverage for various scenarios:

Security Note

Only enable TrustProxy when behind a trusted proxy. Untrusted clients can spoof these headers.