How to Set X-Frame-Options DENY in Flask with a Mock Response

Set the X-Frame-Options header to DENY in a Flask response to prevent clickjacking, and verify it with Flask's test client.

Easy Python 3.9+ Aug 9, 2026 Auth & security at scale 12 views 0 copies

Requires third-party packages — install first
pip install flask

Python code

15 lines
Python 3.9+
from flask import Flask, Response

app = Flask(__name__)

@app.route("/")
def index():
    response = Response("Hello, World!")
    response.headers["X-Frame-Options"] = "DENY"
    return response

if __name__ == "__main__":
    with app.test_client() as client:
        resp = client.get("/")
        print(resp.get_data(as_text=True))
        print(resp.headers.get("X-Frame-Options"))

Output

stdout
Hello, World!
DENY

How it works

The @app.route decorator registers the index function to handle GET requests to /. Inside, a Response object is created with the body string. Setting response.headers['X-Frame-Options'] = 'DENY' adds the HTTP header that instructs browsers not to render the page inside any frame or iframe, mitigating clickjacking attacks. The with app.test_client() block simulates a request without running a live server. client.get('/') returns a response object whose body and headers we print, confirming the header is present.

Common mistakes

  • Setting the header after returning the response, which has no effect.
  • Forgetting to import `Response` from flask or using `make_response` incorrectly.
  • Testing against a live server instead of using the test client for unit tests.

Variations

  1. Use `app.after_request` to add the header globally to all responses.
  2. Set the header with a decorator on the route function using `make_response`.

Real-world use cases

  • Protecting login pages and admin panels from clickjacking attacks.
  • Compliance with security headers policies across a web application.
  • Testing middleware that adds security headers in CI/CD pipelines.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Auth & security at scale

Related tutorials and quizzes for this topic.