To control whether external or same-origin pages can embed your site inside an <iframe> (protecting against clickjacking), configure HTTP response headers on your web server, reverse proxy (Nginx, Apache, Cloudflare), or Node.js application using Content Security Policy (Content-Security-Policy: frame-ancestors ...) as the primary modern standard alongside X-Frame-Options (DENY or SAMEORIGIN) for legacy browser coverage. When frame-ancestors is present in a Content-Security-Policy header, modern browsers ignore X-Frame-Options—and unlike <meta http-equiv="Content-Security-Policy">, frame-ancestors must be delivered as an HTTP response header (it is ignored inside <meta> tags).
1. Configuring Headers in Node.js (HTTP / Middleware)
Set Content-Security-Policy (frame-ancestors) and X-Frame-Options on outgoing HTTP responses, validating allowed origins explicitly instead of blindly echoing untrusted request headers:
// Set safe iframe embedding headers in a Node.js HTTP request handler or middleware
function applyFrameProtectionHeaders(res, { allowedAncestors = ["'self'"], allowSameOriginLegacy = true } = {}) {
if (!res || typeof res.setHeader !== "function") {
throw new TypeError("Expected res to be an HTTP response object with setHeader().");
}
if (!Array.isArray(allowedAncestors) || allowedAncestors.length === 0) {
throw new TypeError("Expected allowedAncestors to be a non-empty array of CSP source expressions.");
}
try {
const sanitizedSources = allowedAncestors.map((src) => {
if (typeof src !== "string" || src.trim().length === 0) {
throw new TypeError("Each CSP frame-ancestors source must be a non-empty string.");
}
return src.trim();
});
const cspDirective = `frame-ancestors ${sanitizedSources.join(" ")}`;
const existingCsp = res.getHeader?.("Content-Security-Policy");
if (typeof existingCsp === "string" && existingCsp.trim().length > 0) {
const updatedCsp = existingCsp.includes("frame-ancestors")
? existingCsp.replace(/frame-ancestors[^;]*/i, cspDirective)
: `${existingCsp.trim()}; ${cspDirective}`;
res.setHeader("Content-Security-Policy", updatedCsp);
} else {
res.setHeader("Content-Security-Policy", cspDirective);
}
const isDenyOnly = sanitizedSources.length === 1 && sanitizedSources[0] === "'none'";
if (isDenyOnly) {
res.setHeader("X-Frame-Options", "DENY");
} else if (allowSameOriginLegacy) {
res.setHeader("X-Frame-Options", "SAMEORIGIN");
}
} catch (error) {
throw new Error(`Failed to apply frame protection headers: ${error.message}`);
}
}
// Example usage:
// applyFrameProtectionHeaders(res, { allowedAncestors: ["'self'", "https://partner.example.com"] });
- Use
frame-ancestors 'none'for full framing denial: Equivalent toX-Frame-Options: DENYacross modern browsers. - Use
frame-ancestors 'self' https://trusted.example.comfor selective embedding:X-Frame-Optionscannot list multiple arbitrary origins cleanly, makingframe-ancestorsessential for multi-origin embedding.
2. Configuring Reverse Proxies (Nginx) and Edge Rules
Configure headers at the edge or reverse proxy so static assets, error pages, and dynamic routes receive consistent framing protection without duplicating header code across every handler:
# Nginx snippet: allow framing only from 'self' and a trusted partner origin
add_header Content-Security-Policy "frame-ancestors 'self' https://partner.example.com;" always;
add_header X-Frame-Options "SAMEORIGIN" always;
- Include
alwaysin Nginxadd_header: Ensures security headers are still emitted on4xxand5xxerror responses, not only200/30xresponses. - Check for duplicate headers across upstream + proxy: Having conflicting
X-Frame-OptionsorContent-Security-Policyheaders from both app and proxy can cause unexpected behavior.
3. Common Pitfalls, Wildcards, and sandbox Attribute Nuances
Watch out for subtle edge cases when locking down or enabling iframes:
- Avoid overly broad wildcards like
*orhttps:: Allowingframe-ancestors *permits any site to frame your pages, undermining clickjacking defense. - Scheme-relative vs. explicit HTTPS origins: Specify full origins with scheme (e.g.,
https://app.example.com) rather than bare hostnames or untrustedhttp://origins. - Sandboxed iframes without
allow-same-originhave an opaque origin: A framed document inside<iframe sandbox="allow-scripts">(withoutallow-same-origin) is treated as an opaque origin, which can affect'self'checks and storage access.