What is clickjacking and how do you prevent it?
SecurityThe short answer
Clickjacking is an attack where a malicious site loads your website in a hidden iframe and tricks users into clicking on it without knowing. The user thinks they are clicking on the malicious page, but they are actually clicking on your hidden page — performing actions like changing settings, making purchases, or granting permissions.
How it works
The attacker creates a page with an invisible iframe on top of visible content:
<!-- Attacker's page --><style> iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; /* invisible */ z-index: 10; /* on top of everything */ }</style><h1>Click here to win a prize!</h1><button>Claim Prize</button><!-- Your site loaded invisibly on top --><iframe src="https://your-site.com/settings/delete-account"></iframe>The user sees "Claim Prize" but actually clicks the "Delete Account" button on your hidden site.
How to prevent it
1. X-Frame-Options header (older approach)
This HTTP header tells the browser whether your site can be loaded in an iframe:
X-Frame-Options: DENY → cannot be framed at allX-Frame-Options: SAMEORIGIN → can only be framed by same origin2. Content-Security-Policy frame-ancestors (modern approach)
Content-Security-Policy: frame-ancestors 'none' → cannot be framedContent-Security-Policy: frame-ancestors 'self' → same origin onlyContent-Security-Policy: frame-ancestors example.com → only by example.comframe-ancestors is more flexible than X-Frame-Options because you can specify multiple allowed origins.
3. JavaScript frame-busting (fallback)
if (window.top !== window.self) { window.top.location = window.self.location;}This checks if your page is loaded in a frame and breaks out of it. However, this is not reliable because the attacker can use the sandbox attribute on the iframe to block JavaScript execution. Use HTTP headers instead.
Interview Tip
When answering, explain the attack first (invisible iframe trick), then cover the defenses. The modern answer is Content-Security-Policy: frame-ancestors. Mention X-Frame-Options as the older approach that is still widely used. Knowing both shows you understand the evolution of web security.
Why interviewers ask this
Clickjacking is a well-known web vulnerability that is easy to prevent but often overlooked. Interviewers want to see if you know about it and if you know how to set the right HTTP headers. It is a quick question that reveals how much you know about web security beyond just XSS and CSRF.