Cloudfront Edge functions

Viewed 19

I'm trying to play Instagram Video assets. The challenge is the videos are expirable. They expire every N mins.

I'm brainstorming a solution where I set up my CDN (Cloudfront) which forwards the incoming requests to the original server (Instagram in this case), caches the video at CDN, and then keeps serving it without the need to request Instagram again. I don't want to download the videos and keep them in my bucket.

I'd a look at CloudFront functions and was able to redirect the incoming requests to another URL, basis on some conditions. Following is the code.

function handler(event) {
    var request = event.request;
    var headers = request.headers;
    
    if request.uri == '/assets/1.jpg'{
        var newurl = 'https://instagram.com/media/1.jpg'
      
        var response = {
            statusCode: 302,
            statusDescription: 'Found',
            headers:
                { "location": { "value": newurl } }
        }

        return response;
     }
   return request
}

However, this redirects it to the newURL. What I'm looking for is not a redirect, but the following

  1. when the request is made to my server CDN, ie mydomain.com/assets/1.jpg, the file 1.jpg should be served from the Instagram server, whose value is the newURL in the above code snippet. This should be done without changing my domain URL (in the address bar) to Instagram.

  2. The following requests to mydomain.com/assets/1.jpg should be directly served from the cache, and should not be routed again to Instagram.

Any help in this regard is highly appreciated.

0 Answers
Related