By default, Flask attaches no security headers to responses, so the browser has to guess how to handle the content — and attackers exploit exactly that gap. A single function with the @app.after_request decorator is all it takes: every response your app sends — HTML, JSON, or error pages — carries the full set of security headers. This works for any Flask app, from a small side project to a production API.
The Problem
The app is already in production. Run curl -I against the homepage and you only see Content-Type, Content-Length, and a few technical headers — no X-Frame-Options, no Content-Security-Policy. The browser is deciding everything on its own, and two risks are wide open.
The first is clickjacking: your login page gets embedded in an iframe on a stranger’s site, and users think they are clicking a button on that site when they are really clicking on yours. The second is MIME sniffing: the browser guesses the type of the returned file, so an uploaded file that looks like an image can be guessed as a script and executed right inside the victim’s browser. Neither needs a bug in your code — just a few missing header lines.
from flask import Flaskapp = Flask(__name__)@app.route("/")def index(): return "<h1>Xin chao</h1>"
$ curl -I http://localhost:5000/HTTP/1.1 200 OKContent-Type: text/html; charset=utf-8Content-Length: 19# Không có X-Frame-Options, không có CSP, không có header bảo mật nào
The Solution
Flask’s after_request hook receives the response before it is sent, modifies its headers, and returns it. Write it once and every route benefits — including JSON responses and 404 error pages.
from flask import Flask, requestapp = Flask(__name__)@app.after_requestdef add_security_headers(response): response.headers["X-Content-Type-Options"] = "nosniff" response.headers["X-Frame-Options"] = "DENY" response.headers["Content-Security-Policy"] = "default-src 'self'" response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin" if request.is_secure: response.headers["Strict-Transport-Security"] = ( "max-age=31536000; includeSubDomains" ) return response
What each header does:
X-Content-Type-Options: nosniff— stops the browser from guessing MIME types, forcing it to honor theContent-Typethe server returns.X-Frame-Options: DENY— forbids embedding the page in an iframe anywhere, blocking clickjacking. If your app embeds itself, useSAMEORIGINinstead.Content-Security-Policy: default-src 'self'— only allows loading resources from your own domain, blocking foreign scripts injected into the page.Referrer-Policy: strict-origin-when-cross-origin— when navigating to another domain, the browser sends only the origin, not the full URL path.Strict-Transport-Security— only set whenrequest.is_secure(the request is running over HTTPS). This header tells the browser to use HTTPS only for a year, so never set it over plain HTTP.
Note: default-src 'self' also blocks CDNs such as Google Fonts or jsDelivr — loosen individual directives, for example by adding script-src 'self' https://cdn.jsdelivr.net, instead of dropping CSP altogether.
Apply It to Your Project
Put this function inside create_app() if you use the Application Factory pattern, so every blueprint is protected without touching each view. After every deploy, run curl -I to check the headers, then score the result at securityheaders.com. For HSTS, wait until HTTPS is running reliably before enabling it, starting from a small max-age. For CSP, start from default-src 'self' and loosen it gradually — a strict CSP you can live with is always better than a perfect one you have to switch off after a week.
Related Posts
- Flask: Log Every Request Automatically with before_request and after_request in 5 Minutes
- Flask: Return Consistent JSON Errors for Your API with app.errorhandler in 5 Minutes
- Flask: Enable CORS Safely with Flask-CORS — Origins and Credentials in 5 Minutes
Frequently Asked Questions
Does after_request run when a view returns a 404 or 500 error?
Yes. Flask calls after_request for every response it creates, including responses from error handlers. I verified this: the 404 page still carries the full set of security headers.
What if CSP default-src ‘self’ blocks my CDN?
Add the domains to individual directives, for example: default-src 'self'; script-src 'self' https://cdn.jsdelivr.net; style-src 'self' https://fonts.googleapis.com.
Should I enable HSTS on the first day I switch to HTTPS?
Wait until HTTPS is running reliably before enabling it: a browser that remembers HSTS will force HTTPS for a whole year, and if you turn HTTPS off afterwards, existing users cannot reach your site. Start with a small max-age, for example 86400 (one day), then increase it gradually.
How is writing this by hand different from using Flask-Talisman?
Flask-Talisman bundles these headers with a CSP that supports nonces — use it when you want a ready-made setup. Write the headers by hand when you want control over each one.
💬 Have you tried this in your own project? If you hit an error or know a shorter way, leave a comment below — I read them all and will add the best ideas to the post.
References
- Flask Documentation —
after_request: https://flask.palletsprojects.com/en/stable/api/#flask.Flask.after_request - MDN Web Docs — X-Content-Type-Options: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options
- OWASP Secure Headers Project: https://owasp.org/www-project-secure-headers/
