Tutorial: Create a serverless notification app with Azure Functions and Azure Web PubSub service

The Azure Web PubSub service helps you build real-time messaging web applications using WebSockets. 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 under notification scenarios.

In this tutorial, you learn how to:

  • Build a serverless notification app
  • Work with Web PubSub function input and output bindings
  • Run the sample functions locally
  • Deploy the function to Azure Function App

Prerequisites

If you don't have an Azure subscription, create an Azure free account before you begin.

Sign in to Azure

Sign in to the Azure portal at https://portal.azure.com/ with your Azure account.

Create an Azure Web PubSub service instance

Your application will connect to a Web PubSub service instance in Azure.

  1. 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.)

    Screenshot of searching the Azure Web PubSub in portal.

  2. Select Web PubSub from the search results, then select Create.

  3. 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.
    Resource Group myResourceGroup Name for the new resource group in which to create your Web PubSub service instance.
    Location West US Choose a region near you.
    Pricing tier Free You can first try Azure Web PubSub service for free. Learn more details about Azure Web PubSub service pricing tiers
    Unit count - 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.

    Screenshot of creating the Azure Web PubSub instance in portal.

  4. Select Create to start deploying the Web PubSub service instance.

Create and run the functions locally

  1. Make sure you have Azure Functions Core Tools installed. And then create an empty directory for the project. Run command under this working directory.

    func init --worker-runtime javascript
    
  2. Install Microsoft.Azure.WebJobs.Extensions.WebPubSub.

    Update host.json's extensionBundle to version 3.3.0 or later to get Web PubSub support.

    {
        "version": "2.0",
        "extensionBundle": {
            "id": "Microsoft.Azure.Functions.ExtensionBundle",
            "version": "[3.3.*, 4.0.0)"
        }
    }
    
  3. Create an index function to read and host a static web page for clients.

    func new -n index -t HttpTrigger
    
    • Update index/function.json and copy following json codes.
      {
          "bindings": [
              {
                  "authLevel": "anonymous",
                  "type": "httpTrigger",
                  "direction": "in",
                  "name": "req",
                  "methods": [
                    "get",
                    "post"
                  ]
              },
              {
                  "type": "http",
                  "direction": "out",
                  "name": "res"
              }
          ]
      }
      
    • Update index/index.js and copy following codes.
      var fs = require('fs');
      var path = require('path');
      
      module.exports = function (context, req) {
          var index = 'index.html';
          if (process.env["HOME"] != null)
          {
              index = path.join(process.env["HOME"], "site", "wwwroot", index);
          }
          context.log("index.html path: " + index);
          fs.readFile(index, 'utf8', function (err, data) {
              if (err) {
                  console.log(err);
                  context.done(err);
              }
              context.res = {
                  status: 200,
                  headers: {
                      'Content-Type': 'text/html'
                  },
                  body: data
              };
              context.done();
          });
      }
      
  4. Create a negotiate function to help clients get service connection url with access token.

    func new -n negotiate -t HttpTrigger
    
    • Update negotiate/function.json and copy following json codes.
      {
          "bindings": [
              {
                  "authLevel": "anonymous",
                  "type": "httpTrigger",
                  "direction": "in",
                  "name": "req"
              },
              {
                  "type": "http",
                  "direction": "out",
                  "name": "res"
              },
              {
                  "type": "webPubSubConnection",
                  "name": "connection",
                  "hub": "notification",
                  "direction": "in"
              }
          ]
      }
      
    • Update negotiate/index.js and copy following codes.
      module.exports = function (context, req, connection) {
          context.res = { body: connection };
          context.done();
      };
      
  5. Create a notification function to generate notifications with TimerTrigger.

     func new -n notification -t TimerTrigger
    
    • Update notification/function.json and copy following json codes.
      {
          "bindings": [
              {
              "name": "myTimer",
              "type": "timerTrigger",
              "direction": "in",
              "schedule": "*/10 * * * * *"
              },
              {
              "type": "webPubSub",
              "name": "actions",
              "hub": "notification",
              "direction": "out"
              }
          ]
      }
      
    • Update notification/index.js and copy following codes.
      module.exports = function (context, myTimer) {
          context.bindings.actions = {
              "actionName": "sendToAll",
              "data": `[DateTime: ${new Date()}] Temperature: ${getValue(22, 1)}\xB0C, Humidity: ${getValue(40, 2)}%`,
              "dataType": "text"
          }
          context.done();
      };
      
      function getValue(baseNum, floatNum) {
          return (baseNum + 2 * floatNum * (Math.random() - 0.5)).toFixed(3);
      }
      
  6. Add the client single page index.html in the project root folder and copy content as below.

    <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>
    
  7. Configure and run the Azure Function app

    • In the browser, open the Azure portal and confirm the Web PubSub Service instance you deployed earlier was successfully created. Navigate to the instance.
    • Select Keys and copy out the connection string.

    Screenshot of copying the Web PubSub connection string.

    Run command below in the function folder to set the service connection string. Replace <connection-string> with your value as needed.

    func settings add WebPubSubConnectionString "<connection-string>"
    

    Note

    TimerTrigger used in the sample has dependency on Azure Storage, but you can use local storage emulator when the Function is running locally. If you got some error like There was an error performing a read operation on the Blob Storage Secret Repository. Please ensure the 'AzureWebJobsStorage' connection string is valid., you'll need to download and enable Storage Emulator.

    Now you're able to run your local function by command below.

    func start
    

    And checking the running logs, you can visit your local host static page by visiting: https://localhost:7071/api/index.

Deploy Function App to Azure

Before you can deploy your function code to Azure, you need to create 3 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 item.

  1. If you haven't done so already, sign in to Azure:

    az login
    
  2. Create a resource group or you can skip by re-using the one of Azure Web PubSub service:

    az group create -n WebPubSubFunction -l <REGION>
    
  3. Create a general-purpose storage account in your resource group and region:

    az storage account create -n <STORAGE_NAME> -l <REGION> -g WebPubSubFunction
    
  4. Create the function app in Azure:

    az functionapp create --resource-group WebPubSubFunction --consumption-plan-location <REGION> --runtime node --runtime-version 14 --functions-version 3 --name <FUNCIONAPP_NAME> --storage-account <STORAGE_NAME>
    

    Note

    If you're running the function version other than v3.0, please check Azure Functions runtime versions documentation to set --runtime-version parameter to supported value.

  5. Deploy the function project to Azure:

    After you've 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> --publish-local-settings
    

    Note

    Here we are deploying local settings local.settings.json together with command parameter --publish-local-settings. If you're using Microsoft Azure Storage Emulator, you can type no to skip overwriting this value on Azure following the prompt message: App setting AzureWebJobsStorage is different between azure and local.settings.json, Would you like to overwrite value in azure? [yes/no/show]. Besides, you can update Function App settings in Azure Portal -> Settings -> Configuration.

  6. Now you can check your site from Azure Function App by navigating to URL: https://<FUNCIONAPP_NAME>.azurewebsites.net/api/index.

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:

  1. 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.

  2. In the window that opens, select the resource group, and then select Delete resource group.

  3. 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.