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?