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

Daniel Brain
2 min readMar 14, 2017

--

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!

--

--