Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cloudflare workers script to enable CORS for fonts
// 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
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
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.