- Courses
- 📚Libraries & Frameworks
- ⚡FastAPI
- Authentication, Authorization and Security
- API Security Best Practices
- HTTP Headers
On this page
HTTP Security Headers in FastAPI
Published on August 14, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
A browser follows whatever instructions a server's response headers give it — whether to guess at a file's content type, whether another site is allowed to embed the current page in an iframe, whether to ever connect over plain HTTP again. Leaving those headers unset doesn't mean "no policy" — it means the browser falls back to its own defaults, which are considerably more permissive than what most applications actually want. Setting them deliberately closes off several categories of attack at once, though which headers actually matter — and how much they matter — depends heavily on whether an application is serving rendered HTML pages or a pure JSON API, a distinction worth being precise about rather than applying every header uniformly regardless of what the application actually returns.
What Security Headers Actually Do
Security headers are instructions from the server to the browser about how to handle a response — they don't validate or transform data the way Pydantic does, and they have no effect at all on non-browser clients like a mobile app or a server-to-server API call, since those never interpret response headers as behavioral instructions the way a browser does. Their value is specifically in constraining what a browser is willing to do with a page once it's loaded — sniff its content type, embed it in a frame, execute inline scripts — closing off exploitation techniques that depend on the browser's default, permissive behavior.
X-Content-Type-Options: Blocking MIME Sniffing
response.headers["X-Content-Type-Options"] = "nosniff"
Without this header, some browsers attempt to guess a response's actual content type by inspecting its bytes, rather than trusting the declared Content-Type header — a file served as Content-Type: text/plain that happens to contain HTML or JavaScript-like content can, in older or misconfigured browser behavior, get interpreted and executed as that guessed type instead. nosniff is the only valid value; it forces the browser to respect the declared Content-Type exactly, closing off this specific class of misinterpretation.
Clickjacking Protection: X-Frame-Options and CSP's frame-ancestors
response.headers["X-Frame-Options"] = "SAMEORIGIN"
X-Frame-Options controls whether a browser is permitted to render a page inside a <frame>, <iframe>, <embed>, or <object> element on another page — DENY blocks framing entirely, SAMEORIGIN allows it only from pages on the same origin. Without this protection, an attacker can layer a transparent iframe of a real page over a deceptive one, tricking a user into clicking something on the real page — a "delete account" or "authorize payment" button — while believing they're interacting with the attacker's page instead. This is clickjacking, and it's the specific attack X-Frame-Options exists to prevent.
X-Frame-Options is now formally obsoleted by the frame-ancestors directive within Content-Security-Policy, which offers the same protection with finer-grained control — multiple allowed origins, wildcard subdomain matching — and standardized, universal support across modern browsers:
response.headers["Content-Security-Policy"] = "frame-ancestors 'self'"
Current guidance is to set both together rather than choosing one over the other: frame-ancestors is honored by modern browsers and takes priority where supported, while X-Frame-Options remains a fallback for any older or less common browser that doesn't yet recognize the CSP directive.
One detail is worth being precise about for a FastAPI application specifically: X-Frame-Options only provides real protection on a response that has interactive content to click on in the first place — a page with buttons, links, forms. A plain JSON API response has nothing for a user to click at all, so setting X-Frame-Options on a /api/users endpoint returning {"users": [...]} provides essentially no security benefit, even though it's harmless to include. This header earns its keep specifically on any endpoint that returns rendered, interactive HTML — a login form, an account settings page — not on JSON responses consumed programmatically by a frontend elsewhere.
Strict-Transport-Security (HSTS)
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
Once a browser receives this header over a genuine HTTPS connection, it remembers to only connect to that domain over HTTPS for the duration specified by max-age (in seconds — 31536000 is one year), even if a user later types http:// explicitly or clicks an old plain-HTTP link. This closes off a specific downgrade attack: an attacker positioned on the network intercepting a plain HTTP request before it gets redirected to HTTPS, and serving a malicious response before the redirect ever happens. includeSubDomains extends that same enforcement to every subdomain of the current one. A preload directive exists as a further step, submitting a domain to a list browsers ship with directly, enforced even on a user's very first visit — but it requires meeting Google's submission requirements and is difficult to reverse quickly once a domain is included, so it's worth adding only once HTTPS is confirmed stable across the entire domain and every subdomain covered by it.
Content-Security-Policy (CSP)
response.headers["Content-Security-Policy"] = "default-src 'self'"
CSP is the most consequential and most complex of these headers — it defines a declarative allow-list of origins a browser is permitted to load resources from, for each resource type independently. default-src 'self' sets the fallback rule: only load resources (scripts, styles, images, fonts) from the page's own origin unless a more specific directive overrides it. A stricter, more explicit policy typically controls each resource type individually rather than relying only on the fallback:
response.headers["Content-Security-Policy"] = (
"default-src 'self'; "
"script-src 'self'; "
"style-src 'self'; "
"img-src 'self' data:; "
"frame-ancestors 'self'"
)
script-src specifically is the highest-impact directive of the set — it controls where executable JavaScript is permitted to load from, and a correctly restrictive script-src is what actually prevents an injected <script> tag from executing even if it somehow made it into a rendered page, since the browser refuses to run a script from an origin the policy doesn't allow. Getting any of these directives wrong in the permissive direction — allowing 'unsafe-inline' for scripts, for instance — meaningfully weakens the protection the rest of the policy is providing.
Referrer-Policy and Permissions-Policy
Two further headers round out a current baseline alongside the four above:
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
response.headers["Permissions-Policy"] = "geolocation=(), microphone=(), camera=()"
Referrer-Policy controls how much of the current page's URL gets sent in the Referer header on outbound requests to other sites — strict-origin-when-cross-origin sends the full URL to same-origin requests but only the bare origin to cross-origin ones, avoiding leaking path or query-string details (which sometimes carry sensitive identifiers) to third parties. Permissions-Policy controls which browser features — camera, microphone, geolocation, and others — a page is allowed to request access to at all; explicitly denying features an application never uses removes them as a possible avenue of abuse entirely, rather than relying on a user noticing and declining a permission prompt that should never have been possible to trigger.
Implementing All Headers with Middleware
from fastapi import FastAPI, Response
app = FastAPI()
@app.middleware("http")
async def add_security_headers(request, call_next):
response: Response = await call_next(request)
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "SAMEORIGIN"
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
response.headers["Content-Security-Policy"] = "default-src 'self'; frame-ancestors 'self'"
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
response.headers["Permissions-Policy"] = "geolocation=(), microphone=(), camera=()"
return response
call_next(request) runs the request through the rest of the application first, and the headers get attached to whatever response comes back — every route in the application receives these headers automatically, with no per-route code needed for any of them.
Where These Headers Matter Most
For an application that renders HTML directly — login pages, dashboards, any server-rendered interface — every header above is doing real, direct work, since a browser is actually parsing and displaying that content. For a pure JSON API, several of these headers still matter (X-Content-Type-Options and Strict-Transport-Security apply regardless of response format), but the clickjacking-focused ones (X-Frame-Options, CSP's frame-ancestors) protect content that doesn't exist in a JSON response — there's nothing framed, nothing clicked. Applying the full header set uniformly across an application is still the simpler and safer default, since it costs nothing on routes where a given header doesn't do much — but understanding which headers are actually earning their place on a given endpoint is what separates a checklist applied blindly from a policy actually understood.
Key Takeaways
Security headers instruct the browser, not the server, and their absence defaults to the browser's own more permissive behavior rather than to "no policy." X-Content-Type-Options: nosniff and Strict-Transport-Security apply their protection regardless of response format, while X-Frame-Options and CSP's frame-ancestors directive — now the standard, recommended mechanism for clickjacking defense, with X-Frame-Options kept alongside it purely as a legacy fallback — only provide meaningful protection on responses with actual interactive content, not on plain JSON. Content-Security-Policy is the most consequential header of the set, with script-src in particular determining whether an injected script could ever actually execute even if it reached a rendered page. Applying the full set through a single middleware function is what makes this consistent across every route in an application, without needing to remember to set anything per-endpoint.
Practice: Extending the Middleware
@app.middleware("http")
async def add_security_headers(request, call_next):
response: Response = await call_next(request)
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "SAMEORIGIN"
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
response.headers["Content-Security-Policy"] = "default-src 'self'; frame-ancestors 'self'"
return response
X-Frame-Options: SAMEORIGIN and Content-Security-Policy: default-src 'self' (with frame-ancestors 'self' folded into the same policy for the modern equivalent) are both present here, matching the specific compliance requirement of allowing the application's own pages to frame each other while blocking every other origin from doing so.
Testing that the validated CommentCreate model from earlier correctly accepts and safely neutralizes an XSS payload rather than executing it:
curl -X POST http://127.0.0.1:8000/comments \
-H "Content-Type: application/json" \
-d '{"text": "<script>alert(\"xss\")</script>"}'
A correctly configured endpoint returns 201 Created with the comment stored exactly as submitted — the string itself, unmodified, since validation's job is confirming it's a well-formed string within the length limit, not deciding whether it's safe to render. Fetching that comment back through a route using Jinja2Templates and checking the rendered page's HTML source, rather than viewing it through the browser's normal display, confirms the payload appears as <script>alert("xss")</script> — visible as literal text, never executed — which is the autoescaping behavior covered directly, doing its job at the one place that actually needed it.
Frequently Asked Questions
Do security headers protect a mobile app or a server-to-server API call the same way they protect a browser?
No. Security headers are instructions a browser interprets and enforces — a mobile app, curl, or a server-to-server request never applies these behaviors at all, since nothing about that client reads response headers as policy the way a browser does. These headers specifically protect browser-based clients rendering or interacting with the response.
Is it worth setting X-Frame-Options and CSP's frame-ancestors on a pure JSON API endpoint?
It's harmless but provides little real protection there. X-Frame-Options and frame-ancestors defend against clickjacking, which requires interactive content — buttons, links, forms — for a user to be tricked into clicking. A JSON response has nothing to click, so there's no clickjacking surface to protect on that specific endpoint, even though setting the header doesn't cause any harm.
Should I remove X-Frame-Options now that CSP's frame-ancestors directive replaces it?
No — current guidance is to keep both together rather than dropping one. frame-ancestors is the modern, more capable mechanism and takes priority in browsers that support it, but X-Frame-Options remains a necessary fallback for any browser or environment that doesn't yet recognize the CSP directive.
My Content-Security-Policy is blocking legitimate scripts or styles from loading. How do I fix this without disabling CSP?
This means default-src 'self' (or a more specific directive like script-src) doesn't include an origin the page actually needs — a CDN, an analytics script, an embedded widget. The fix is adding that specific origin to the relevant directive (e.g., script-src 'self' https://cdn.example.com), not removing the policy or reaching for 'unsafe-inline', which meaningfully weakens the protection CSP is providing.
Why does my HSTS header have no effect when I test the site locally over HTTP?
Strict-Transport-Security only takes effect once a browser receives it over a genuine HTTPS connection — a browser has no reason to trust or remember an HSTS instruction delivered over plain HTTP, since that connection could already be intercepted. Testing HSTS behavior requires HTTPS actually configured, even in a local or staging environment.
Is it safe to enable HSTS preload right away?
Not necessarily. Preload submits a domain to a list browsers ship with directly, enforced from a user's very first visit, before any single HSTS header has ever been received — but it's difficult to reverse quickly once a domain is included. It's worth adding only after confirming HTTPS is stable and fully working across the entire domain and every subdomain it would cover.
What's the difference between setting these headers per-route versus through middleware?
Middleware applies the headers to every response automatically, since call_next(request) runs the request through the rest of the app first and the headers get attached to whatever comes back — no route needs to remember to set anything individually. Setting headers per-route only makes sense when a specific endpoint genuinely needs a different policy than the rest of the application.
Does Permissions-Policy need to list every browser feature, or just the ones I want to block?
Only the features relevant to the application need addressing — commonly by explicitly denying ones it never uses, like geolocation=(), microphone=(), camera=(). There's no requirement to enumerate every possible feature; the policy only needs to cover what's meaningful to restrict for that specific application.
I set Content-Security-Policy but my browser's dev tools still show inline <script> tags executing. Why?
Check whether the policy includes 'unsafe-inline' in script-src, or whether default-src is being relied on without an explicit script-src override that excludes it. A policy permitting 'unsafe-inline' allows inline scripts to execute regardless of origin restrictions elsewhere in the policy, which defeats much of CSP's protection against injected scripts specifically.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Input Sanitization
Next
Building Your First API — Task Manager (Part 3)
- What Security Headers Actually Do
- X-Content-Type-Options: Blocking MIME Sniffing
- Clickjacking Protection: X-Frame-Options and CSP's frame-ancestors
- Strict-Transport-Security (HSTS)
- Content-Security-Policy (CSP)
- Referrer-Policy and Permissions-Policy
- Implementing All Headers with Middleware
- Where These Headers Matter Most
- Key Takeaways
- Practice: Extending the Middleware
- Frequently Asked Questions
