Secure headers help protect your website from common attacks by telling browsers how to behave safely.
Secure headers configuration in Flask
from flask import Flask, make_response app = Flask(__name__) @app.after_request def set_secure_headers(response): response.headers['Content-Security-Policy'] = "default-src 'self'" response.headers['X-Content-Type-Options'] = 'nosniff' response.headers['X-Frame-Options'] = 'DENY' response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains' response.headers['Referrer-Policy'] = 'no-referrer' return response
The @app.after_request decorator lets you add headers to every response.
Headers are set by adding key-value pairs to response.headers.
response.headers['X-Frame-Options'] = 'DENY'
response.headers['Content-Security-Policy'] = "default-src 'self'"
response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
This Flask app adds important security headers to every response to protect users and the site.
Visit the home page to see the content, and check browser DevTools to see the headers.
from flask import Flask, make_response app = Flask(__name__) @app.after_request def set_secure_headers(response): response.headers['Content-Security-Policy'] = "default-src 'self'" response.headers['X-Content-Type-Options'] = 'nosniff' response.headers['X-Frame-Options'] = 'DENY' response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains' response.headers['Referrer-Policy'] = 'no-referrer' return response @app.route('/') def home(): return '<h1>Welcome to Secure Flask App</h1>' if __name__ == '__main__': app.run(debug=True)
Use browser DevTools (Network tab) to check if headers are correctly set.
Be careful with Content-Security-Policy; too strict rules can block needed resources.
Always test your site after adding headers to avoid breaking functionality.
Secure headers help protect your site from attacks by guiding browser behavior.
Flask lets you add headers easily using @app.after_request.
Common headers include Content-Security-Policy, X-Frame-Options, and Strict-Transport-Security.