17 Jan 2021

Solving "No 'Access-Control-Allow-Origin' header is present on the requested resource"

You've probably encountered this annoying error before when requesting resources over the network from a domain that's different than the one serving your web app.

For content that is served by an API, this is quite straight-forward to solve: modify your apps to accept and respond to these cross-domain requests. However, for static files this might be a bit tricky as there is no app that serves the file as it is directly served from the server, 100% static. You may encounter this scenario when you have a CDN that serves assets from an origin that is also managed by you.

Let's consider the case for NakedSSL: we have the app living on app.nakedssl.com and the CDN living on cdn.nakedssl.com. The CDN is configured in a way that, when requesting cdn.nakedssl.com/assets/*, it will fetch assets from app.nakedssl.com/assets/* and serve them under cdn.nakedssl.com/assets/*. What may happen when our app tries to load assets from cdn.nakedssl.com? Yep, exactly: I'll most likely get the damn "No 'Access-Control-Allow-Origin' header is present on the requested resource" error in the browser.

While the issue might a bit hard to explain and even harder to notice before you experience it, it is actually surprisingly easy to solve: it is as simple as allowing cross-domain requests on your origin. You can do that by just adding the following piece of code to the VirtualHost file that controls the origin from where the CDN requests the assets:

If you use Nginx:

location ~* .
(json|gif|jpg|jpeg|png|ico|wmv|3gp|avi|mpg|mpeg|mp4|flv|mp3|mid|js|css|wml|swf|ttf|ttc|otf|eot|woff|woff2)$ { add_header Access-Control-Allow-Origin "*";
expires max; }

If you use Apache:

# Allow access from all domains for webfonts.
# Alternatively you could only whitelist your
# subdomains like "subdomain.example.com". <IfModule mod_headers.c>
<FilesMatch "\.
(json|gif|jpg|jpeg|png|ico|wmv|3gp|avi|mpg|mpeg|mp4|flv|mp3|mid|js|css|wml|swf|ttf|ttc|otf|eot|woff|woff2)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>

Et voilà, the error is solved. If you still encounter issues, there might be one more thing left to do: ensure that your CDN is configured to forward headers from/to your client and origin.


🤖 Happy coding 🤖

Wanna join us as a Product Developer? Then drop us a line.