Tutorial: Create a serverless real-time chat app with Azure Functions and Azure Web PubSub service
Article
12/11/2024
The Azure Web PubSub service helps you build real-time messaging web applications using WebSockets and the publish-subscribe pattern easily. Azure Functions is a serverless platform that lets you run your code without managing any infrastructure. In this tutorial, you learn how to use Azure Web PubSub service and Azure Functions to build a serverless application with real-time messaging and the publish-subscribe pattern.
In this tutorial, you learn how to:
Build a serverless real-time chat app
Work with Web PubSub function trigger bindings and output bindings
Deploy the function to Azure Function App
Configure Azure Authentication
Configure Web PubSub Event Handler to route events and messages to the application
Important
Raw connection strings appear in this article for demonstration purposes only.
A connection string includes the authorization information required for your application to access Azure Web PubSub service. The access key inside the connection string is similar to a root password for your service. In production environments, always protect your access keys. Use Azure Key Vault to manage and rotate your keys securely and secure your connection with WebPubSubServiceClient.
Avoid distributing access keys to other users, hard-coding them, or saving them anywhere in plain text that is accessible to others. Rotate your keys if you believe they may have been compromised.
Your application will connect to a Web PubSub service instance in Azure.
Select the New button found on the upper left-hand corner of the Azure portal. In the New screen, type Web PubSub in the search box and press enter. (You could also search the Azure Web PubSub from the Web category.)
Select Web PubSub from the search results, then select Create.
Enter the following settings.
Setting
Suggested value
Description
Resource name
Globally unique name
The globally unique Name that identifies your new Web PubSub service instance. Valid characters are a-z, A-Z, 0-9, and -.
Subscription
Your subscription
The Azure subscription under which this new Web PubSub service instance is created.
Unit count specifies how many connections your Web PubSub service instance can accept. Each unit supports 1,000 concurrent connections at most. It is only configurable in the Standard tier.
Select Create to start deploying the Web PubSub service instance.
Create the functions
Make sure you have Azure Functions Core Tools installed. And then create an empty directory for the project. Run command under this working directory.
Update __init__.py and replace main function with following codes.
import os
import azure.functions as func
def main(req: func.HttpRequest) -> func.HttpResponse:
f = open(os.path.dirname(os.path.realpath(__file__)) + "/../index.html")
return func.HttpResponse(f.read(), mimetype="text/html")
Create a negotiate function to help clients get service connection url with access token.
func new -n negotiate -t HttpTrigger
Note
In this sample, we use Microsoft Entra ID user identity header x-ms-client-principal-name to retrieve userId. And this won't work in a local function. You can make it empty or change to other ways to get or generate userId when playing in local. For example, let client type a user name and pass it in query like ?user={$username} when call negotiate function to get service connection url. And in the negotiate function, set userId with value {query.user}.
Before you can deploy your function code to Azure, you need to create three resources:
A resource group, which is a logical container for related resources.
A storage account, which is used to maintain state and other information about your functions.
A function app, which provides the environment for executing your function code. A function app maps to your local function project and lets you group functions as a logical unit for easier management, deployment and sharing of resources.
Use the following commands to create these items.
If you haven't done so already, sign in to Azure:
az login
Create a resource group or you can skip by reusing the one of Azure Web PubSub service:
az group create -n WebPubSubFunction -l <REGION>
Create a general-purpose storage account in your resource group and region:
az storage account create -n <STORAGE_NAME> -l <REGION> -g WebPubSubFunction
az functionapp create --resource-group WebPubSubFunction --consumption-plan-location <REGION> --runtime python --runtime-version 3.9 --functions-version 4 --name <FUNCIONAPP_NAME> --os-type linux --storage-account <STORAGE_NAME>
Deploy the function project to Azure:
After you have successfully created your function app in Azure, you're now ready to deploy your local functions project by using the func azure functionapp publish command.
func azure functionapp publish <FUNCIONAPP_NAME>
Configure the WebPubSubConnectionString for the function app:
Raw connection strings appear in this article for demonstration purposes only. In production environments, always protect your access keys. Use Azure Key Vault to manage and rotate your keys securely and secure your connection with WebPubSubServiceClient.
First, find your Web PubSub resource from Azure Portal and copy out the connection string under Keys. Then, navigate to Function App settings in Azure Portal -> Settings -> Environment variables. And add a new item under App settings, with name equals WebPubSubConnectionString and value is your Web PubSub resource connection string.
Configure the Web PubSub service Event Handler
In this sample, we're using WebPubSubTrigger to listen to service upstream requests. So Web PubSub need to know the function's endpoint information in order to send target client requests. And Azure Function App requires a system key for security regarding extension-specific webhook methods. In the previous step after we deployed the Function App with message functions, we're able to get the system key.
Go to Azure portal -> Find your Function App resource -> App keys -> System keys -> webpubsub_extension. Copy out the value as <APP_KEY>.
Set Event Handler in Azure Web PubSub service. Go to Azure portal -> Find your Web PubSub resource -> Settings. Add a new hub settings mapping to the one function in use. Replace the <FUNCTIONAPP_NAME> and <APP_KEY> to yours.
System Events: -(No need to configure in this sample)
Configure to enable client authentication
Go to Azure portal -> Find your Function App resource -> Authentication. Click Add identity provider. Set App Service authentication settings to Allow unauthenticated access, so your client index page can be visited by anonymous users before redirect to authenticate. Then Save.
Here we choose Microsoft as identify provider, which uses x-ms-client-principal-name as userId in the negotiate function. Besides, you can configure other identity providers following the links, and don't forget update the userId value in negotiate function accordingly.
Now you're able to test your page from your function app: https://<FUNCTIONAPP_NAME>.azurewebsites.net/api/index. See snapshot.
Click login to auth yourself.
Type message in the input box to chat.
In the message function, we broadcast caller's message to all clients and return caller with message [SYSTEM] ack. So we can know in sample chat snapshot, first four messages are from current client and last two messages are from another client.
Clean up resources
If you're not going to continue to use this app, delete all resources created by this doc with the following steps so you don't incur any charges:
In the Azure portal, select Resource groups on the far left, and then select the resource group you created. You may use the search box to find the resource group by its name instead.
In the window that opens, select the resource group, and then select Delete resource group.
In the new window, type the name of the resource group to delete, and then select Delete.
Next steps
In this quickstart, you learned how to run a serverless chat application. Now, you could start to build your own application.
Change a JavaScript web app update mechanism from polling to real-time push-based architecture with SignalR Service, Azure Cosmos DB and Azure Functions. Use Vue.js and JavaScript to use SignalR using Visual Studio Code.
Build end-to-end solutions in Microsoft Azure to create Azure Functions, implement and manage web apps, develop solutions utilizing Azure storage, and more.