Skip to main content
Launch demo
demo introduction

Create a Chat app

Prerequisites

  1. Node.js
  2. Create an Azure Web PubSub resource
  3. localtunnel to expose our localhost to internet

Setup

npm install

Start the app

Copy Connection String from Keys tab of the created Azure Web PubSub service, and replace the <connection-string> below with the value of your Connection String.

Connection String

Linux:

export WebPubSubConnectionString="<connection_string>"
node server

Windows:

SET WebPubSubConnectionString=<connection_string>
node server

The web app is listening to event handler requests at http://localhost:8080/eventhandler.

Use localtunnel to expose localhost

localtunnel is an open-source project that help expose your localhost to public. Install the tool and run:

lt --port 8080 --print-requests

localtunnel will print out an url (https://<domain-name>.loca.lt) that can be accessed from internet, e.g. https://xxx.loca.lt.

Tip: There is one known issue that localtunnel goes offline when the server restarts and here is the workaround

There are also other tools to choose when debugging the webhook locally, for example, ngrokloophole, TunnelRelay or so. Some tools might have issue returning response headers correctly. Try the following command to see if the tool is working properly:

curl https://<domain-name>.loca.lt/eventhandler -X OPTIONS -H "WebHook-Request-Origin: *" -H "ce-awpsversion: 1.0" --ssl-no-revoke -i

Check if the response header contains webhook-allowed-origin: *. This curl command actually checks if the WebHook abuse protection request can response with the expected header.

Configure the event handler

Event handler can be set from portal or through Azure CLI, here contains the detailed instructions for how to.

Go to the Settings tab to configure the event handler for this chat hub:

  1. Click "Add" to add settings for hub sample_chat.

  2. Set URL Pattern to https://<domain-name>.loca.lt/eventhandler and check connected in System Event Pattern, click "Save".

    Event Handler

Start the chat

Open http://localhost:8080/index.html, input your user name, and send messages.

You can see in the localtunnel command window that there are requests coming in with every message sent from the page.

Client using json.webpubsub.azure.v1 subprotocol

Besides the simple WebSocket client we show in index.html, fancy.html shows a client using json.webpubsub.azure.v1 achieving the same by sending message event to the service. With the help of the subprotocol, the client can get connected and disconnected messages containing some metadata of the connection.

You can open both http://localhost:8080/index.html and http://localhost:8080/fancy.html to see messages received by both clients.