Search code examples
amazon-web-serviceswebsocketaws-api-gatewayamazon-cloudfrontaws-lambda-edge

can i use a cloudfront function to change url in the behaviour path pattern


Followup question for this

I have 2 websocket APIs
Foo WebSocket API - wss://x5g9h3p2rq.execute-api.eu-central-1.amazonaws.com/dev
Bar WebSocket API - wss://r2h6k1v8nm.execute-api.eu-central-1.amazonaws.com/dev

In my distribution, I created 2 origins for these 2 API gateways. Then I created 2 behaviours for those origins with following path patterns
foo-socket - /dev/foo-socket/*
bar-socket - /dev/bar-socket/*

My goal is to connect to the respective socket APIs from the browser like wss://my-custom-domain/dev/foo-socket/ and wss://my-custom-domain/dev/bar-socket/

For this to work I had to associate a Lambda@Edge to the Origin request which strips the /foo-socket/ or /bar-socket/ from the request URI to just /dev since the WebSocket API doesn't accept path parameters other than the stage they provide.

Is this possible with CloudFront functions instead since this is just a URL rewrite in a way? I feel like Lambda@Edge adds some latency and it harms the real-time aspects a bit

Help is much appreciated. Thanks in advance!


Solution

  • i tried Cloudfront function and it worked

    • Removed the Lambda@Edge associated with the Origin Request
    • Created a cloudfront function that looks like
    function handler(event) {
        var request = event.request;
        request.uri = request.uri.replace(/\/[^\/]+\/$/, '');
        return request;
    }
    
    • Here I change the uri of the request from /dev/foo-socket/ to /dev. Since I'm returning the modified request I associated it with Viewer Request. Make sure to publish the function as well.

    NOTE
    cannot use es6 syntax in the function and have to stick with es5 var. You will get 503 errors saying and FunctionExecutionErrors from cloudfront. Thanks to this (it is not in english tho)