Skip to main content

Overview

The header middleware provides flexible request and response header manipulation. Add, modify, or remove headers for security, caching, or custom requirements.

Installation

Quick Start

Functions

Response Headers

Request Headers

Security Headers

Content Headers

Examples

Set Single Header

Set Multiple Headers

Remove Headers

Security Headers

HSTS

Content Security Policy

Full Configuration

API Reference

Technical Details

Architecture

The header middleware is built on the WithOptions function, which serves as the core implementation. All other functions (Set, New, Remove, etc.) are convenience wrappers that delegate to WithOptions with specific configurations.

Options Structure

Execution Flow

  1. Request Phase (before handler):
    • Sets request headers from Options.Request
    • Removes request headers from Options.RequestRemove
    • Sets response headers from Options.Response
  2. Handler Execution: Calls the next middleware/handler
  3. Response Phase (after handler):
    • Removes response headers from Options.ResponseRemove

Implementation Notes

  • Request headers are set before the handler executes, making them available to downstream handlers
  • Response headers are set before the handler but can be overridden by the handler
  • Response header removal happens after the handler executes to ensure headers set by the handler are properly removed
  • The middleware uses a custom itoa function for integer-to-string conversion to avoid unnecessary allocations in HSTS header generation

Best Practices

  • Use WithOptions for complex configurations involving multiple header operations
  • Use convenience functions (Set, Remove, etc.) for simple single-header operations
  • Set security headers at the application level rather than per-route
  • Remove sensitive headers (e.g., Server, X-Powered-By) to avoid information disclosure
  • Chain multiple header middlewares when you need different headers for different routes

Testing

The header middleware includes comprehensive test coverage for all functions:
  • helmet - Comprehensive security headers