Security headers middleware — X-Frame-Options, X-Content-Type-Options, Referrer-Policy.
Adds common security headers to HTML responses per HTML Living Standard recommendations (clickjacking, MIME sniffing, referrer leakage).
Headers are applied only to text/html responses. Skipped for JSON, SSE, static files, and other non-HTML content types.
middleware.security_headers
| Name | Type | Default | Description |
|---|---|---|---|
type
|
|
— | |
qualified_name
|
|
— | |
element_type
|
|
— | |
description
|
|
— | |
source_file
|
|
— | |
line_number
|
|
— | |
is_autodoc
|
|
— | |
autodoc_element
|
|
— | |
_autodoc_template
|
|
— | |
_autodoc_url_path
|
|
— | |
_autodoc_page_type
|
|
— | |
title
|
|
— | |
doc_content_hash
|
|
— |
Symbols on this page
Configuration for security headers.
All values are applied as-is. Use standard header values.
True if response is HTML and should receive security headers.
Add security headers to a Response, StreamingResponse, or FileResponse.
Add security headers to HTML responses.
Per HTML spec recommendations:
- X-Frame-Options — prevents clickjacking
- X-Content-Type-Options — prevents MIME sniffing
- Referrer-Policy — controls referrer leakage…
SecurityHeadersConfig
class
Configuration for security headers.
All values are applied as-is. Use standard header values.
_is_html_response
function
def _is_html_response(response: AnyResponse) -> bool
True if response is HTML and should receive security headers.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
response
|
AnyResponse
|
— |
_add_headers
function
def _add_headers(response: Response | StreamingResponse | FileResponse, config: SecurityHeadersConfig) -> AnyResponse
Add security headers to a Response, StreamingResponse, or FileResponse.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
response
|
Response | StreamingResponse | FileResponse
|
— | |
config
|
SecurityHeadersConfig
|
— |
SecurityHeadersMiddleware
class
Add security headers to HTML responses.
Per HTML spec recommendations:
- X-Frame-Options — prevents clickjacking
- X-Content-Type-Options — prevents MIME sniffing
- Referrer-Policy — controls referrer leakage
Usage::
from chirp.middleware import SecurityHeadersMiddleware
app.add_middleware(SecurityHeadersMiddleware())
Or with custom config::
from chirp.middleware.security_headers import (
SecurityHeadersConfig,
SecurityHeadersMiddleware,
)
app.add_middleware(SecurityHeadersMiddleware(SecurityHeadersConfig(
x_frame_options="SAMEORIGIN",
)))
View source · /home/runner/work/chirp/chirp/site/../src/chirp/middleware/security_headers.py:1