Call Azure Function From SPFX Webpart

In this article, I am going to walk you through the architectural journey of calling an Azure Function from an SPFx web part. We will cover the security handshake and the configuration with a real-time example.

Call Azure Function From SPFX Webpart

Why Connect SPFx to Azure Functions?

Before we discuss the “how,” we must establish the “why.

When you build an SPFx web part, the code is visible to the user. If you “Inspect Element” in Chrome, you can see everything. This creates three specific problems that Azure Functions solve:

  1. Security via Obscurity: You cannot store secrets (like an API key for a third-party service like Salesforce or a weather API) in your SPFx code. If you do, anyone with a browser can steal it. An Azure Function acts as a proxy, holding the secrets securely on the server side.

  2. CORS (Cross-Origin Resource Sharing): Many external APIs do not allow calls directly from a SharePoint domain. Azure Functions can bypass this by acting as the middleman.

  3. Heavy Lifting: If you are processing thousands of rows of data, doing it in the browser will freeze the user’s UI. Azure Functions offload this processing to the cloud.

Combining the serverless power of Azure Functions with the frontend versatility of SPFx is, in my opinion, the gold standard for modern Microsoft 365 development.

If you have requirements for working outside SharePoint, Azure Functions is one of the best options.

What exactly will we perform here?

  • We will create an Azure HTTP-triggered Function.
  • The next step is to see how to consume the Azure Function from the SharePoint Framework Client WebPart.

Create The Azure Function

Azure Functions is a Microsoft Azure service that lets you run code to perform tasks without worrying about your application’s infrastructure.

Well, let’s create an Azure HTTP-triggered function using the Azure Portal. Follow the steps below to create the Azure Function

Follow the steps below to create Azure functions in the Azure portal.

1. Log in to Azure Portal (https://portal.azure.com/)

2. As highlighted below, click on the  + Create a resource, and click on “Compute”. Now, choose the “Function App.”

How To Create Azure Function Apps In The Azure Portal

Or, for the exact Option, you can search for the Function App and click on the search result.

Azure Function Creation using Azure Portal

From the next step onwards, You can follow my article to create the Azure Function App using the Azure Portal to create the Azure Function App. Assuming your Azure Function App is ready.

Now is the time to create the HTTP-triggered Azure Function, since our Azure Function App is ready.

To create an Azure Function, click on the Functions link in the left navigation and then click the + Add button.

SharePoint Framework - Call Azure Function

Select the HTTP trigger template, enter a name, set the Authorization level to Anonymous, and click the Create Function button.

Call Azure Function from Sharepoint Framework

Below is the default code for my Azure Function app

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{ log.LogInformation("My Azure function processed a request.");    
    
    string name = req.Query["name"];    
    
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();    
    dynamic data = JsonConvert.DeserializeObject(requestBody);    
    name = name ?? data?.name;    
    
    return name != null    
        ? (ActionResult)new OkObjectResult(new { name = $"Hello, {name}"} )    
        : new BadRequestObjectResult(new { name = " name you need to pass on the query string or request body"});    
}

You can see the same here

call azure function from spfx webpart

Now, just to make sure the Azure Function is working, click Test/Run, enter a value for the name parameter in the body, and click Run. You can see it ran successfully for me, and I got the perfect Response Code.

spfx call azure function

Now, click on the Get Function URL button next to the Test/Run button. Then copy the URL and keep it with you. We need to use that URL in our code next. I have copied the URL, and it is as follows

https://mydemofunctionspfx.azurewebsites.net/api/MyHttpTrigger

SahrePoint Framework Call Azure Function

Set Up CORS on the Azure Function

Open the Azure Function App that you have created above, and then click on CORS from the left navigation, provide the local host URL and  Office 365 tenant domain URL, and then click on the save button.

How to call Azure Function from SPFX

Create a SharePoint Framework Webpart

Now that our Azure Function part creation is over. This is the time to create the SharePoint framework webpart. Follow the steps below to make the SharePoint framework webpart.

The first step is to create a directory where we will build the project. For that, open the command prompt and run the command below to create the directory

md spfx-azure-function-demo 
Create SharePoint Framework Webpart to call Azure Function

Navigate to the spfx-azure-function-demo directory using the command below

cd spfx-azure-function-demo

Now the next step is to create the solution. Run the Yeoman SharePoint Generator to create the spfx web part solution. Execute the command as mentioned below.

yo @microsoft/sharepoint

Now, it will ask you to provide the details below

SPFX webpart to call the Azure Function

What is your solution name?: You can type a solution name, or if you want to keep the default name, you can just hit Enter.

My Selected Value: Just Hit Enter

Target environment: Select the environment where the webpat will be deployed.

My Selected Value: SharePoint Online only (latest)

Where do you want to place the files?: Where you want to keep your files. You can either choose the current folder or create a subfolder under the Project folder.

My Selected Value: Same folder

Deployment option: If you select the Y option, the webpart will be deployed to all sites. It’s better to select the N option here.

My Selected Value: N

Which type of client-side component to create? You can create the webpart or Extension.

My Selected Value: Webpart

Name of the Webpart: Provide a name for the webpart.

My Selected Value: SPFXAzureFunction

What is your Web part description? You can type a description for the Web part, or press Enter to keep the default description.

My Selected Value: This webpart will call the Azure Function

Which framework would you like to use? You can use different frameworks like No JavaScript Framework, React, and Knockout. You can choose the No JavaScript Framework.

My Selected Value: No JavaScript Framework

You can able to see below all the provided options to create the SPFX client-side webpart

How to create SPFX webpart to call the Azure Function

Now Yeoman generator will start creating the solution based on the input provided above. Now you can able to see the solution has been created successfully without any issues.

How to call Azure Function from SPFX webpart

Now, to lock the version of the project dependencies, you can run the following command

npm shrinkwrap

Now, to open the code editor, type the code space dot(.) command.

code .

Check the code now

You can see the solution that has been created below

Azure Function with SPFx

The next step is to open the SpfxAzureFunctionWebPart.ts file, which is present in the “srcwebpartsSpfxAzureFunctionWebPart” path. And add the below import statement

import { HttpClient, SPHttpClient, HttpClientConfiguration, HttpClientResponse, ODataVersion, IHttpClientConfiguration, IHttpClientOptions, ISPHttpClientOptions } from '@microsoft/sp-http';  

It would be best if you mentioned the Function URL below

protected functionUrl: string = "https://mydemofunctionspfx.azurewebsites.net/api/MyHttpTrigger";    

Add one IInfo.ts file in the “srcwebpartsSpfxAzureFunction” path. It should contain the code below

export interface IInfo {
    name?: string;
}

Now you need to add the import statement below to the SpfxAzureFunctionWebPart.ts file, which is present in the “srcwebpartsSpfxAzureFunctionWebPart” path. And add the below import statement.

import { IInfo } from './IInfo';

Below is the code for my RetrieveAzureFunction() function.

export default class SpfxAzureFunctionWebPart extends BaseClientSideWebPart <ISpfxAzureFunctionWebPartProps> {
  protected functionUrl: string = "https://mydemofunctionspfx.azurewebsites.net/api/MyHttpTrigger";
  protected RetrieveAzureFunction(): void {    
    const requestHeaders: Headers = new Headers();    
    requestHeaders.append("Content-type", "text/plain");    
    requestHeaders.append("Cache-Control", "no-cache");    
  
    var siteUrl: string = this.context.pageContext.web.absoluteUrl;    
    var firstname: string = (<HTMLInputElement>document.getElementById("txtFirstName")).value;    
      console.log(`SiteUrl: '${siteUrl}', FirstName: '${firstname}'`);    
      const postOptions: IHttpClientOptions = {    
      headers: requestHeaders,    
      body: `{ name: '${firstname}' }`    
    };    
      let responseText1: string = "";    
    let result: HTMLElement = document.getElementById("responseContainer");    
      this.context.httpClient.post(this.functionUrl, HttpClient.configurations.v1, postOptions).then((response: HttpClientResponse) => {    
       response.json().then((JSONresp: IInfo) => {    
          
          if (response.ok) {    
              //Write something here;    
          } else {    
              //Write something here;    
          }    
  
          result.innerText = JSONresp.name;    
        })    
        .catch ((response: any) => {    
          let err: string = `Error calling URL ${this.functionUrl}. Error = ${response.message}`;        
          console.log(err);    
          result.innerText = err;    
        });    
    });    
}    

The code below is my Render() method.

this.domElement.innerHTML = `   
    <input type="text" id="txtFirstName"></input>    <br/>
    <button id="btnRetrieveAzureFunction" >Hello</button>     
      `;    
    
      document.getElementById("btnRetrieveAzureFunction").onclick = this.RetrieveAzureFunction.bind(this);

Run the SharePoint Framework Webpart

Now, in your command prompt, run gulp clean, gulp build, and then finally, gulp serve

Navigate to the Sharepoint workbench, i.e., https://your SharePoint site/_layouts/15/workbench.aspx, and add the webpart.

Provide a first name in the text box and then click on the Hello button. It will show you the expected Output.

Azure Function, Connect To SharePoint

As part of this functionality, we will create an Azure Function App to delete a SharePoint list using CSOM.

Delete SharePoint Online List From Azure Function App

The first step is to create an Azure Function App using the Azure Portal

Follow the above-mentioned steps that we have discussed already at the start of the article to create an Azure Function App. Below is the Azure Function App that I have created.

Azure Function, Connect To SharePoint

Now, our Function App is ready, so we will create our Azure Function. We will create that using Visual Studio 2019.

So, create the Azure function using Visual Studio now. You can see my Azure Function project is ready now, as shown below

Delete SharePoint Online List From Azure Function App visual studio 2019

Now, you can use the code below for your Azure Function

using System;
using System.IO;
using System.Threading.Tasks;
//using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
//using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Collections.Generic;
using Microsoft.SharePoint.Client;
using System.Net;
using System.Net.Http;
//using Microsoft.AspNetCore.Mvc.WebApiCompatShim;
using System.Linq;

namespace deletesplistvs
{
    public static class Function1
    {
        [FunctionName("NewFunction")]
        public static async Task<HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage request,
            ILogger log)
        {

            string site = "https://tsinfo.sharepoint.com/sites/SPFx/";
            string userName = "test@tsinfo.onmicrosoft.com";
            string password = "####@12345";


            // parse query parameter  
            string listtitle = request.GetQueryNameValuePairs()
                .FirstOrDefault(q => string.Compare(q.Key, "title", true) == 0)
                .Value;


            System.Security.SecureString secureString = new System.Security.SecureString();
            foreach (char ch in password)
            {
                secureString.AppendChar(ch);
            }

            SharePointOnlineCredentials creds = new SharePointOnlineCredentials(userName, secureString);

            using (var ctx = new ClientContext(site))
            {
                ctx.Credentials = creds;
                List lst = ctx.Web.Lists.GetByTitle(listtitle);
                lst.DeleteObject();
                ctx.ExecuteQuery();
                return lst == null
                ? request.CreateResponse(HttpStatusCode.BadRequest, "Error retreiveing the list")
                : request.CreateResponse(HttpStatusCode.OK, "List Deleted successfully " + listtitle);
            }
            return null;
        }
    }
}

Make sure to make the below changes to the projectname.csproj file

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net461</TargetFramework>
    <AzureFunctionsVersion>v1</AzureFunctionsVersion>
  </PropertyGroup>

You can test it locally. Press F5 and then copy and paste the function URL with title value as a query string parameter, like below

http://localhost:7071/api/NewFunction?title=testlist

You can see the list was deleted successfully

Delete SharePoint Online List From Azure Function

Now, right-click on the solution and click on the Publish button

Select the existing option from the next window, and then choose the Azure Function App that we have created above, and click on the OK button.

How to Delete SharePoint Online List From Azure Function App visual studio

Now, click on the Publish button to publish the Azure Function to Azure

How to Delete SharePoint Online List From Azure Function visual studio 2019

Now log in to the Azure Portal and navigate to the Azure Function App we created above, click on the functions option from the left side, and click on the Function we published just now.

Click on the Get function URL button, copy the URL, and keep it. The URL should be like below

https://connecttosharepoint12.azurewebsites.net/api/NewFunction?code=Ywz0yHIlFxol2BqaZDdC5xLvyESRffgCTPh5mqLyyZ/UutI0n0vebQ==

How to Delete SharePoint Online List From Azure Function

Now open your favorite browser and pass the title value as a query string parameter. Testing is the name of my list.

https://connecttosharepoint12.azurewebsites.net/api/NewFunction?code=Ywz0yHIlFxol2BqaZDdC5xLvyESRffgCTPh5mqLyyZ/UutI0n0vebQ==&title=testing

You can see below that the SharePoint list was deleted successfully

Delete SharePoint Online List From Azure Function CSOM

You can also able to delete the SharePoint list from the Azure Portal

Delete SharePoint Online List From Azure Function App using Azure Portal

Our Function App is ready now. Let’s create the Azure Function now. You can again follow the steps mentioned above to create the HTTP-triggered Azure Function. You can choose the HTTP trigger template, provide the Function name, choose the Authorization level as Function, and click on the Create Function button to create the Azure Function.

image

Now the Azure Function is created as below

image 1

Now, navigate to the Azure Function App, click on the Advanced Tools link from the left navigation, and then click on the Go button.

image 2

Click on the CMD option from the Debug console drop-down.

image 3

Click on the site folder.

image 4

Now, you can click on the wwwroot folder.

image 5

You can see the function name. You can click on that

image 6

Click on the + and then New folder, and you can name it bin.

image 7

Now you can download the two DLLs below and drag them to the folder

image 8

Now navigate to the Azure Function again and click on the Code + Test link you can use the below namespaces and the code from the above

#r "Newtonsoft.Json"
#r "Microsoft.SharePoint.Client.dll"  
#r "Microsoft.SharePoint.Client.Runtime.dll"  
  
using System.Net;  
using Microsoft.SharePoint.Client; 

Now, if you click on the Get Function URL button, copy that and append the title value like above, and access it from your browser to see the expected output.

Best Practices for Production

If you are deploying this for a Fortune 500 company, “it works on my machine” is not enough.

1. Use Application Insights

Always connect your Azure Function to Application Insights. You need to know if the function is failing or running slowly. You can even log custom events from SPFx to App Insights to trace the full user journey.

2. Version Your API

Don’t just call /api/MyFunction. Call /api/v1/MyFunction. Someday, you will need to change the logic without breaking the existing web parts deployed across your SharePoint environment.

3. Keep Payloads Small

SharePoint pages are already heavy. Do not return 10MB of JSON from your Azure Function. Filter the data on the server side (in Azure) and send only exactly what the web part needs to render.

Wrapping Up

Connecting an SPFx Web Part to an Azure Function is a rite of passage for modern Microsoft 365 developers. It creates a bridge between the friendly, user-centric world of SharePoint and the limitless, secure computational power of the Azure Cloud.

While the setup involves a fair amount of configuration—bouncing between the Azure Portal, the SharePoint Admin Center, and your local code—the result is a robust, secure, and enterprise-grade solution.

You may also like to follow the articles below

Azure Virtual Machine

DOWNLOAD FREE AZURE VIRTUAL MACHINE PDF

Download our free 25+ page Azure Virtual Machine guide and master cloud deployment today!