{"id":3997,"date":"2023-11-04T23:13:59","date_gmt":"2023-11-04T23:13:59","guid":{"rendered":"http:\/\/localhost:10003\/building-a-scalable-web-app-with-azure-functions-and-signalr\/"},"modified":"2023-11-05T05:48:24","modified_gmt":"2023-11-05T05:48:24","slug":"building-a-scalable-web-app-with-azure-functions-and-signalr","status":"publish","type":"post","link":"http:\/\/localhost:10003\/building-a-scalable-web-app-with-azure-functions-and-signalr\/","title":{"rendered":"Building a scalable web app with Azure Functions and SignalR"},"content":{"rendered":"
Azure Functions and SignalR are two powerful tools that can be used together to create a scalable web app. Azure Functions is a serverless compute service that allows you to run your code on-demand, without the need to provision or manage virtual machines. SignalR is a real-time communication framework that enables bi-directional communication between clients and servers. In this tutorial, we will show you how to use Azure Functions and SignalR to build a scalable web app.<\/p>\n
Before we start, you will need to have the following:<\/p>\n
The first step is to set up Azure Functions and SignalR. Follow these steps to create a new Azure Functions app and a SignalR service:<\/p>\n
Next, we need to set up a front-end client that will communicate with our Azure Functions app and SignalR service. We will use a simple HTML file with some JavaScript code to create our front-end client.<\/p>\n
<!DOCTYPE html>\n<html>\n<head>\n <title>Chat<\/title>\n <script src=\"https:\/\/code.jquery.com\/jquery-3.5.1.min.js\"><\/script>\n <script src=\"https:\/\/cdn.jsdelivr.net\/npm\/@microsoft\/signalr@3.1.8\/dist\/browser\/signalr.min.js\"><\/script>\n<\/head>\n<body>\n <h1>Chat<\/h1>\n <div>\n <input type=\"text\" id=\"username\" placeholder=\"Enter your username\" \/>\n <button id=\"join\">Join<\/button>\n <\/div>\n <div>\n <textarea id=\"messages\" cols=\"50\" rows=\"10\"><\/textarea>\n <\/div>\n <div>\n <input type=\"text\" id=\"message\" placeholder=\"Enter your message\" \/>\n <button id=\"send\">Send<\/button>\n <\/div>\n <script>\n \/\/ TODO: Add SignalR client code here\n <\/script>\n<\/body>\n<\/html>\n<\/code><\/pre>\nThis code creates a simple chat UI with an input field to enter your username, a button to join the chat, a textarea to display all the messages, an input field to enter your message, and a button to send your message.<\/p>\n
\n- Add the following code inside the
TODO<\/code> block to create a SignalR client and handle the “join” and “send” button clicks:<\/li>\n<\/ol>\nconst usernameInput = document.getElementById(\"username\");\nconst joinButton = document.getElementById(\"join\");\nconst messagesTextarea = document.getElementById(\"messages\");\nconst messageInput = document.getElementById(\"message\");\nconst sendButton = document.getElementById(\"send\");\n\n\/\/ Create a new SignalR connection\nconst connection = new signalR.HubConnectionBuilder()\n .withUrl(\"https:\/\/your-signalr-service-name.service.signalr.net\/client\/?access_token=your-access-token\")\n .configureLogging(signalR.LogLevel.Information)\n .build();\n\n\/\/ Handle the \"join\" button click\njoinButton.addEventListener(\"click\", async () => {\n const username = usernameInput.value;\n await connection.start();\n connection.invoke(\"Join\", username);\n});\n\n\/\/ Handle the \"send\" button click\nsendButton.addEventListener(\"click\", async () => {\n const message = messageInput.value;\n const username = usernameInput.value;\n connection.invoke(\"Send\", username, message);\n messageInput.value = \"\";\n});\n\n\/\/ Handle incoming messages\nconnection.on(\"ReceiveMessage\", (username, message) => {\n messagesTextarea.value += `${username}: ${message}n`;\n});\n<\/code><\/pre>\nThis code creates a new SignalR connection, handles the “join” button click by starting the connection and invoking the “Join” method on the server, handles the “send” button click by invoking the “Send” method on the server and clearing the message input field, and handles incoming messages by appending them to the textarea.<\/p>\n
Step 3 – Set up Azure Functions<\/h2>\n
Now that we have our front-end client set up, we need to create some Azure Functions that will handle the “Join” and “Send” methods on the server.<\/p>\n
\n- Open the “index.js” file in your project directory and replace the existing code with the following code:<\/li>\n<\/ol>\n
const { CosmosClient } = require(\"@azure\/cosmos\");\nconst { v4: uuidv4 } = require(\"uuid\");\nconst signalR = require(\"@microsoft\/signalr\");\n\nconst connectionString = \"your-cosmos-db-connection-string\";\nconst containerName = \"messages\";\nconst databaseName = \"chat\";\n\nmodule.exports = async function (context, req) {\n const client = new CosmosClient(connectionString);\n const database = client.database(databaseName);\n const container = database.container(containerName);\n\n if (req.query.method === \"Join\") {\n await join(context, container, req.body);\n } else if (req.query.method === \"Send\") {\n await send(context, container, req.body);\n } else {\n context.res = {\n status: 400,\n body: \"Invalid method\"\n };\n }\n};\n\nasync function join(context, container, payload) {\n const id = uuidv4();\n const username = payload;\n const item = {\n id: id,\n username: username,\n message: \"joined the chat\"\n };\n await container.items.create(item);\n\n const connection = new signalR.HubConnectionBuilder()\n .withUrl(\"https:\/\/your-signalr-service-name.service.signalr.net\/client\/?acce<div>ss_token=your-access-token\")\n .configureLogging(signalR.LogLevel.Information)\n .build();\n\n connection.on(\"Send\", async (username, message) => {\n const id = uuidv4();\n const item = {\n id: id,\n username: username,\n message: message\n };\n await container.items.create(item);\n\n context.bindings.signalRMessage = {\n target: \"ReceiveMessage\",\n arguments: [username, message]\n };\n });\n\n await connection.start();\n}\n\nasync function send(context, container, payload) {\n const id = uuidv4();\n const { username, message } = payload;\n const item = {\n id: id,\n username: username,\n message: message\n };\n await container.items.create(item);\n\n context.bindings.signalRMessage = {\n target: \"ReceiveMessage\",\n arguments: [username, message]\n };\n}\n<\/code><\/pre>\nThis code creates two Azure Functions: one to handle the “Join” method, and one to handle the “Send” method. It also connects to an Azure Cosmos DB instance to store and retrieve chat messages.<\/p>\n
The “join” function generates a unique ID for the user, creates a new item in the Cosmos DB container to indicate that the user has joined the chat, creates a new SignalR connection for the user, and listens for incoming messages. When a message is received, the function creates a new item in the Cosmos DB container to store the message, and sends a SignalR message to all connected clients with the “ReceiveMessage” target and the sender’s username and message as arguments.<\/p>\n
The “send” function generates a unique ID for the message, creates a new item in the Cosmos DB container to store the message, and sends a SignalR message to all connected clients with the “ReceiveMessage” target and the sender’s username and message as arguments.<\/p>\n
Step 4 – Test the web app<\/h2>\n
Now that we have everything set up, it’s time to test our web app and see if everything works as expected.<\/p>\n
\n- Start by running your Azure Functions app locally:\n
\n- Open the “Azure Functions” extension in Visual Studio Code<\/li>\n
- Click the “Run” button or press
F5<\/code><\/li>\n<\/ul>\n<\/li>\n- Navigate to the “index.html” file in your project directory and open it in your web browser.<\/p>\n<\/li>\n
- \n
Enter a unique username and click the “Join” button.<\/p>\n<\/li>\n
- \n
Open a new tab or window and navigate to the “index.html” file again.<\/p>\n<\/li>\n
- \n
Enter a different unique username and click the “Join” button.<\/p>\n<\/li>\n
- \n
Go back to the first tab or window and enter a message in the input field.<\/p>\n<\/li>\n
- \n
Click the “Send” button. You should see the message appear in the textarea in both tabs or windows.<\/p>\n<\/li>\n
- \n
Congratulations! You have created a scalable web app with Azure Functions and SignalR.<\/p>\n<\/li>\n<\/ol>\n
Conclusion<\/h2>\n
In this tutorial, we showed you how to use Azure Functions and SignalR to create a scalable web app. We walked you through the process of setting up Azure Functions and SignalR, creating a simple front-end client, creating Azure Functions to handle the “Join” and “Send” methods, and testing the web app. By leveraging the power of these two tools, you can create a real-time communication app that can scale to millions of users without worry.<\/p>\n","protected":false},"excerpt":{"rendered":"
Azure Functions and SignalR are two powerful tools that can be used together to create a scalable web app. Azure Functions is a serverless compute service that allows you to run your code on-demand, without the need to provision or manage virtual machines. SignalR is a real-time communication framework that Continue Reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[585,30,203,766,49,765],"yoast_head":"\nBuilding a scalable web app with Azure Functions and SignalR - Pantherax Blogs<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n