Add an Access-Control-Allow-Origin Header using Cloudflare Workers

If you have set a cookie free domain or CDN and your fonts are broken and not showing then it might be due to Cross-Origin Resource Sharing (CORS). There should be a way to control what resources from my site is sharable and what are not. So that I can prevent content from my site from being used by others. That’s why CORS is needed.

Here my site does not mean only my site but any other sites. And CORS not only protects resources but also sensitive data by disallowing AJAX request from unknown websites. But this also has a disadvantage, the reason you are here.

To allow certain resource to be shared by other websites like fonts you have to add <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin">Access-Control-Allow-Origin</a> header in that resource. Without it when you try to access fonts from subdomain or CDN browser shows warning message in console. You can access console by entering Ctrl+Shift+I in any browser but don’t forget to reload the page.

One can add Access-Control-Allow-Origin by editing .htaccess (in Apache) or some server files. But if you use Cloudflare with your cookie free subdomain then there is no need to touch any server files to add this header. You can do it using Cloudflare Workers.

Gist link – https://gist.github.com/2shrestha22/381256503f236661aba4b68df0109bbd

// Sets Access-Control-Allow-Origin for fonts
// this worker should be used in subdomain from where fonts are being loaded but not in main site
// eg. www.example.com & static.example.com
// use this worker script with static.example.com
//don't forget to replace domain name
let corsHeaders = {
  "Access-Control-Allow-Origin" : "https://sangams.com.np",
}
addEventListener('fetch', event => {
	event.respondWith(addHeaders(event.request))
})
async function addHeaders(req) {
	let response = await fetch(req)
	let newHdrs = new Headers(response.headers)
   if (newHdrs.has("Content-Type") && !(newHdrs.get("Content-Type").includes("font")) ) {
        return new Response(response.body , {
            status: response.status,
            statusText: response.statusText,
            headers: newHdrs
        })
	}
	Object.keys(corsHeaders).map(function(name, index) {
		newHdrs.append(name, corsHeaders[name]);
	})
	return new Response(response.body , {
		status: response.status,
		statusText: response.statusText,
		headers: newHdrs
	})
}

Create a new worker with above script and enable it on your static subdomian. And don’t forget to replace https://sangams.com.np with your main domain name.

Cloudflare Worker is amazing, isn’t it? See How to decrease TTFB and dramatically boost loading speed using Cloudflare Workers.

Finally it will load all the fonts which are not loading due to CORS because above script appends Access-Control-Allow-Origin header in all the fonts which are requested by the main domain. The final result will look like this.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.