0

I have a React TS browser app with Azure Functions back end that I am trying to implement WebSockets in using Azure Web PubSub.

Following the guide at https://learn.microsoft.com/en-us/azure/azure-web-pubsub/tutorial-serverless-notification?tabs=csharp I can get the Azure Functions to Web PubSub side working, but in the example the client page is within the Azure Functions app. The following code snippets are from the guide.

Azure Function for negotiating PubSub connection and getting access token:

[FunctionName("negotiate")]
public static WebPubSubConnection Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
    [WebPubSubConnection(Hub = "notification")] WebPubSubConnection connection,
    ILogger log)
{
    log.LogInformation("Connecting...");

    return connection;
}

Simple client page:

<html>
    <body>
    <h1>Azure Web PubSub Notification</h1>
    <div id="messages"></div>
    <script>
        (async function () {
            let messages = document.querySelector('#messages');
            let res = await fetch(`${window.location.origin}/api/negotiate`);
            let url = await res.json();
            let ws = new WebSocket(url.url);
            ws.onopen = () => console.log('connected');

            ws.onmessage = event => {
                let m = document.createElement('p');
                m.innerText = event.data;
                messages.appendChild(m);
            };
        })();
    </script>
    </body>
</html>

I run this locally on http://localhost:7071 and can successfully negotiate, connect to the WS, and display messages.

If I try and connect my React front end app (http://localhost:3000), I can still hit the negotiate function in my function app, but then get a CORS error when trying to connect to the WS.

Presumably I could handle the negotiate within the React app, but that would mean storing the Azure PubSub access token in React. Any better way to do this?

Neil
  • 159
  • 10
  • So the main issue is that my front end and back end are sitting on different domains. This is fine for the normal working of the application as the backend explicitly accepts the front end as an origin. The Azure Web PubSub tooling (Microsoft.Azure.WebJobs.Extensions.WebPubSub) doesn't like this though and doesn't seem to have any way to specify acceptable origins. For now I'm testing working around it by proxying the frontend from within the Azure Functions app. – Neil Feb 15 '23 at 16:40

0 Answers0