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.