Allowing multiple domains to render your app in an iframe, using X-FRAME-OPTIONS

I get this question a lot — especially from people building iframe-based components with zoid. The question is “how do I whitelist multiple domains with X-FRAME-OPTIONS?”

The answer is pretty simple (and it works for any iframe): have the client pass along the domain when you create the iframe! Here’s an example.

First, on the client, let’s create our iframe, and pass along the domain:

// Set up the url for our iframe, and get the current domainvar url    = 'https://www.my-site.com';
var domain = window.location.protocol + '//' + window.location.host;
// Create the iframevar iframe = document.createElement('iframe');
document.body.appendChild(iframe);
// Set the src, and pass along the domain as a query paramiframe.src = url + '?domain=' + domain;

Then on our server side, we can make the decision whether or not to allow the domain:

// Set up a whitelist of domains that can render us in an iframevar XFRAME_WHITELIST = [ 'https://x.com', 'https://y.com' ];// If the domain matches, allow iframes from that domainif (XFRAME_WHITELIST.indexOf(req.query.domain) !== -1) {
res.header('X-FRAME-OPTIONS', 'ALLOW-FROM ' + req.query.domain);
}

This example is in node.js / express.js, but this logic works no matter your server platform.

You can also use thereferer header instead of a query param, but note that referer is not guaranteed to be present 100% of the time.

This also works perfectly if you’re building a cross-domain component using zoid:

var url    = 'https://www.mysite.com/mycomponent';
var domain = window.location.protocol + '//' + window.location.host;

var MyComponent = zoid.create({
url: url + '?domain=' + domain
});

And if you’re interested in learning more about using zoid to create cross-domain components, please feel free to take a look:

https://medium.com/@bluepnume/introducing-xcomponent-seamless-cross-domain-web-components-from-paypal-c0144f3e82bf

Thanks!

works for PayPal, as a lead engineer in Checkout. Opinions expressed herein belong to him and not his employer. daniel@bluesuncorp.co.uk

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store