Skip to content

Instantly share code, notes, and snippets.

@n-ramdi
Created April 29, 2021 08:27
Show Gist options
  • Save n-ramdi/9fd83c543c5a47bfb819e3deb2ca43bb to your computer and use it in GitHub Desktop.
Save n-ramdi/9fd83c543c5a47bfb819e3deb2ca43bb to your computer and use it in GitHub Desktop.
Cloudflare worker to bypass Instagram new cross-origin policy on images (fixes net :: ERR_BLOCKED_BY_RESPONSE )
// Instagram started setting cross-origin-resource-policy: same-origin when it sees bad referer headers.
// this change leads to ERR_BLOCKED_BY_RESPONSE error and broken images if instagram image is embedded to external website.
// to mitigate this, simple image proxy can be used.
// Steps to install this worker:
// 1. Create CNAME cdn.<yourdomain.com> in your CloudFlare panel
// 2. Create new worker and put the code below into the worker code
// 3. Setup worker route so the worker launches on your cdn. subdomain.
// 4. Modify your image urls from
// https://scontent-arn2-1.cdninstagram.com/v/t51.2885-15/sh0xxx.jpg
// to:
// https://cdn.<YOURDOMAIN>/https://scontent-arn2-1.cdninstagram.com/v/t51.2885-15/sh0xxx.jpg
async function handleRequest(request) {
let url = new URL(request.url)
// If this is a good url - proxy it to instagram
if (url.pathname.includes('cdninstagram.com')) {
let newUrl = url.pathname.replace(/^\/+/, '').replace('https:/', 'https://') + url.search
let response = await fetch(newUrl.toString(), request)
// Recreate the response so we can modify the headers
response = new Response(response.body, response)
// change header from 'same-origin'
response.headers.set('cross-origin-resource-policy', 'cross-origin')
return response
}
// Otherwise, process request as normal
return new Response("Bad url", { status: 404 })
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment