jlobos / instagram-web-api

🤳 Instagram Private Web API client for Node
https://npmjs.com/instagram-web-api
MIT License
1.12k stars 186 forks source link

Instagram added cross-origin-resource-policy: same-origin ? #248

Open thetoine opened 3 years ago

thetoine commented 3 years ago

This is not 100% related to this project but directly impacted. I noticed since a few days ago that Instagram is blocking hot linking to images outside its domain.

image

Am I alone experiencing this? I can't figure if they blocked our domain or if it's a new recent policy.

thetoine commented 3 years ago

Hello,

Replying to myself here. But hey, here's some insights!

I managed to find a work around for this using a CloudFlare Worker. Basically, the worker wrap the request and change the cross-origin policy with response.headers.set("Cross-Origin-Resource-Policy", "cross-origin")

On a plain regular img tag :

<img src="https://instagram-cors-worker.your-company.workers.dev/?image_url=https%3A%2F%2Fcdn.instagram..." />

CF Worker :

async function handleRequest(request) {
  const url = new URL(request.url)
  let image_url = url.searchParams.get("image_url")

  if(!image_url) return new Response("Error. No image_url URL param detected", {status: 500})

  // Rewrite request to point to API url. This also makes the request mutable
  // so we can add the correct Origin header to make the API server think
  // that this request isn't cross-site.
  request = new Request(image_url, request)
  request.headers.set("Origin", new URL(image_url).origin)
  let response = await fetch(request)

  // Recreate the response so we can modify the headers
  response = new Response(response.body, response)

  // Set CORS headers
  response.headers.set("Cross-Origin-Resource-Policy", "cross-origin")

  // Append to/Add Vary header so browser will cache response correctly
  response.headers.append("Vary", "Origin")

  return response
}

addEventListener('fetch', async event => {
  event.respondWith(handleRequest(event.request))
})

Hope this helps anyone.

MindsetZack commented 3 years ago

You are not alone. I am getting the same error as you, "Specify a more permissive Cross-Origin Resource Policy to prevent a resource from being blocked"

Tried to get it working but had no luck but shall try your approach and see how I fair!

NithinSGowda commented 3 years ago

I had the same issue, I built this package to solve the issue https://www.npmjs.com/package/pass-cors

Its simple to use, The img tag becomes

<img src="/proxy?url=https://instagram-cors-worker.your-company.workers.dev/?image_url=https%3A%2F%2Fcdn.instagram...">

And now all Instagram API images load on my frontend. Refer to the package link for more documentation