X-Frame-Options and Frame Ancestors
What you'll learn: How to prevent clickjacking attacks by controlling whether your website can be embedded in frames or iframes on other domains.
The Clickjacking Threat
Imagine a malicious website that loads your banking site in an invisible iframe, then overlays fake buttons. When users think they're clicking "Play Video," they're actually clicking "Transfer $1000" on the hidden frame beneath. This is clickjacking—tricking users into performing unintended actions by disguising your legitimate page inside another site's frame.
X-Frame-Options: The Original Defense
The X-Frame-Options HTTP header tells browsers whether your page can be embedded in frames:
X-Frame-Options: DENY
- DENY: Cannot be framed at all, anywhere
- SAMEORIGIN: Can only be framed by pages from your own domain
- ALLOW-FROM uri: Can be framed only by specified URI (deprecated, poorly supported)
Think of this as a "Do Not Frame Me" sticker on your webpage. Browsers honor it by refusing to display your content inside frames from unauthorized sources.
Frame-Ancestors: The Modern Approach
X-Frame-Options has limitations and is being replaced by the more flexible frame-ancestors directive in Content Security Policy (CSP):
Content-Security-Policy: frame-ancestors 'none';
Content-Security-Policy: frame-ancestors 'self';
Content-Security-Policy: frame-ancestors https://trusted.example.com;
This gives you granular control: allow framing from nowhere, only your domain, or specific trusted domains. You can list multiple sources, unlike the old ALLOW-FROM.
Best Practice
Use both for backward compatibility with older browsers, ensuring frame-ancestors matches your X-Frame-Options policy. Apply this to any page containing sensitive actions or data.
Key Takeaway: Use X-Frame-Options: DENY or SAMEORIGIN (legacy) and CSP's frame-ancestors directive (modern) to prevent attackers from embedding your site in malicious frames and performing clickjacking attacks.