How to Call an Azure Function from an SPFx Web Part (Complete Guide)

If you’ve been building SPFx web parts for a while, you’ve probably hit a wall at some point. You need to run some server-side code — maybe call a third-party API with a secret key, process a big dataset, or do something your SharePoint front-end just can’t do on its own. That’s exactly where Azure Functions come in.

In this guide, I’ll walk you through everything, from creating a simple Azure Function to calling it securely from your SPFx web part. I’ll cover two methods: the simpler anonymous/HttpClient approach, and the proper production-ready approach using Azure AD-secured functions with AadHttpClient. By the end, you’ll know exactly when to use which one.

Why Would You Even Need This?

Before we write any code, let me explain the “why” because it matters.

When you write an SPFx web part, your JavaScript code runs in the user’s browser. Anyone can open DevTools and inspect everything. That creates a few real problems:

  • You can’t store secrets. API keys, passwords, connection strings — none of that belongs in SPFx code. Anyone can steal them.
  • CORS gets in the way. Many external APIs flat-out refuse calls from a SharePoint domain. Azure Functions act as a middle layer that bypasses this cleanly.
  • Heavy processing kills UX. If you’re crunching thousands of rows or running complex business logic in the browser, it freezes up. Move that work to Azure.

An Azure Function solves all three. It sits in the cloud, holds your secrets safely, and does the heavy lifting — your SPFx web part just calls it and waits for results.

What We’ll Build

Here’s the overall picture:

  1. Create an HTTP-triggered Azure Function
  2. Configure CORS on it
  3. Build an SPFx web part
  4. Call the function from the web part using two different approaches:
    • Method 1 — HttpClient (for anonymous/open functions, good for testing)
    • Method 2 — AadHttpClient (for Azure AD-secured functions, the right choice for production)

If you want to learn SharePoint Framework, then check out the SPFx training course.

Part 1: Create Your Azure Function

Step 1: Set Up a Function App in Azure Portal

Head over to portal.azure.com and follow these steps:

  1. Click + Create a resource â†’ search for Function App â†’ click Create
  2. Fill in the basics:
    • Subscription â€” pick yours
    • Resource group â€” create a new one or use an existing one
    • Function App name â€” something like spfx-demo-functions
    • Runtime stack â€” Node.js or .NET, your call
    • Region â€” pick one close to your users
  3. Click through to Review + Create â†’ Create
how to create azure function app

Give it a minute or two to deploy.

Step 2: Create an HTTP-Triggered Function

Once your Function App is ready:

  1. Go into your Function App → click Functions in the left menu → + Add
  2. Select HTTP trigger as the template
create a http triggered function app on azure
  1. Give it a name, like GetEmployeeData
  2. Set the Authorization level to Anonymous for now (we’ll change this for the secure method)
  3. Click Create
azure function http trigger authentication

Here’s a simple example of what the function code looks like (Node.js):

module.exports = async function (context, req) {
context.log('SPFx called this function.');

const name = req.query.name;

if (name) {
context.res = {
status: 200,
body: {
message: `Hello, ${name}! Response from Azure.`
}
};
} else {
context.res = {
status: 400,
body: {
message: "Please pass a name in the query string."
}
};
}
};
azure function http trigger example for spfx

Click Save, then test it using the Test/Run panel. If you get a 200 response — you’re good.

Step 3: Copy Your Function URL

Click Get Function URL and copy it. It’ll look like:

https://spfx-demo-functions-hqhmfndwepfjgfar.canadacentral-01.azurewebsites.net/api/GetEmployeeData
azure function http trigger post body spfx example

Keep this handy. You’ll need it in the web part code.

Step 4: Configure CORS

This is the step people forget, and then spend an hour debugging a random browser error.

  1. In your Function App, click CORS in the left navigation
  2. Add the following origins:
    • https://yourtenant.sharepoint.com (replace with your actual SharePoint domain)
    • https://localhost:4321 (for local SPFx workbench testing)
  3. Click Save
spfx azure function

Without this, your SharePoint page will get a CORS error the moment it tries to call the function, even if the function URL itself works fine in a browser.

Part 2: Create the SPFx Web Part

Step 1: Scaffold the Project

Open a terminal/command prompt and run:

md spfx-azure-demo
cd spfx-azure-demo
yo @microsoft/sharepoint

When Yeoman asks you questions, answer like this:

  • Solution name: spfx-azure-demo
  • Target environment: SharePoint Online only (latest)
  • Place files: Same folder
  • Component to create: WebPart
  • Web part name: AzureFunctionDemo
  • Framework: No JavaScript framework (or React if you prefer)
create spfx webpart using react step by step

Once scaffolding is done, open the project in VS Code:

code .

Method 1: Calling an Anonymous Azure Function with HttpClient

This is the straightforward approach. If your Azure Function’s authorization level is set to Anonymous, you can call it with the built-in HttpClient. Think of this as the “quick prototype” method.

Step 1: Import HttpClient

Open src/webparts/azureFunctionDemo/AzureFunctionDemoWebPart.ts and add this import at the top:

import {
HttpClient,
HttpClientResponse,
IHttpClientOptions
} from '@microsoft/sp-http';

Step 2: Add the Function Call Logic

Here’s a clean method that calls the function and displays the result:

export interface IAzureFunctionDemoState {
result: string;
isLoading: boolean;
}

const FUNCTION_URL: string = 'https://spfx-demo-functions-hqhmfndwepfjgfar.canadacentral-01.azurewebsites.net/api/GetEmployeeData';

export default class AzureFunctionDemo extends React.Component<IAzureFunctionDemoProps, IAzureFunctionDemoState> {
constructor(props: IAzureFunctionDemoProps) {
super(props);
this.state = {
result: '',
isLoading: false
};
}

private callAzureFunction = (): void => {
this.setState({ isLoading: true, result: '' });

const userName = encodeURIComponent(this.props.userDisplayName);

const functionUrl = `${FUNCTION_URL}?name=${userName}`;

this.props.httpClient
.get(functionUrl, HttpClient.configurations.v1)
.then((response: HttpClientResponse) => response.json())
.then((data: { message: string }) => {
this.setState({
result: data.message,
isLoading: false
});
})
.catch((error: Error) => {
this.setState({
result: `Error: ${error.message}`,
isLoading: false
});
});
}

public render(): React.ReactElement<IAzureFunctionDemoProps> {

const { result, isLoading } = this.state;

return (
<section className={`${styles.azureFunctionDemo} `}>
<div>
<h3>Azure Function Demo</h3>
<button disabled={isLoading} onClick={this.callAzureFunction}>
{isLoading ? 'Calling...' : 'Call Azure Function'}
</button>
<div style={{ marginTop: 10 }}>{result}</div>
</div>
</section>
);
}
}

Step 3: Test It

Run the local workbench:

Heft start --clean

Navigate to https://yourtenant.sharepoint.com/_layouts/15/workbench.aspx, add your web part, and click the button. If everything is wired up correctly, you’ll see the response from Azure displayed on screen.

call azure function from spfx

This works perfectly for anonymous functions. But don’t use this in production with sensitive data — your function URL would be exposed with no authentication protecting it.

Method 2: Calling an Azure AD-Secured Function with AadHttpClient

This is the right way to do it in a real production environment. Here, the Azure Function is protected by Azure Active Directory (now called Microsoft Entra ID), and your SPFx web part authenticates using OAuth tokens — no passwords or secrets in your code.

This method uses AadHttpClient, which automatically acquires and sends a Microsoft Entra ID access token when calling a protected API. This lets your SPFx web part securely call an Azure Function without having to implement the OAuth flow yourself.

Step 1: Register Your Azure Function in Azure AD

First, you need to give your Azure Function an identity in Azure AD:

  1. Go to Azure Portal â†’ Azure Active Directory â†’ App registrations â†’ + New registration
  2. Give it a name like SPFx-AzureFunction-API
  3. Set the Redirect URI to Web → https://spfx-demo-functions.azurewebsites.net/.auth/login/aad/callback
  4. Click Register
spfx call azure function authentication
  1. Go to Expose an API â†’ click Add a scope
  2. Set the Application ID URI (Azure will suggest one — accept it)
  3. Add a scope like user_impersonation, set admin consent required, and save
aadhttpclient spfx

Copy the Application (client) ID â€” you’ll need it.

Step 2: Enable Azure AD Auth on the Function App

  1. In your Function App → click Authentication in the left menu
  2. Click Add identity provider
  3. Configure the following:
SettingValue
Identity providerMicrosoft
TenantWorkforce configuration (current tenant)
App registrationPick an existing app registration in this directory
App registrationSPFx-AzureFunction-API
Client application requirementAllow requests from any application
Restrict accessRequire authentication
Unauthenticated requestsHTTP 401 Unauthorized
enable azure ad auth on the function app 1

Click Add. Your Azure Function is now secured — unauthenticated calls will get a 401.

Step 3: Request Permissions in Your SPFx Project

Open config/package-solution.json and add a webApiPermissionRequests block:

{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "spfx-azure-demo-client-side-solution",
"id": "your-solution-id-here",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"webApiPermissionRequests": [
{
"resource": "SPFx-AzureFunction-API",
"scope": "user_impersonation"
}
]
},
"paths": {
"zippedPackage": "solution/spfx-azure-demo.sppkg"
}
}

The resource value here is the display name of your Azure AD app registration — the same one you created in Step 1.

Step 4: Use AadHttpClient in Your Web Part

Now update your web part code. The AadHttpClient looks very similar to HttpClient, but it automatically handles token acquisition:

import { AadHttpClient, HttpClientResponse } from '@microsoft/sp-http';

export default class AzureFunctionDemoWebPart extends BaseClientSideWebPart<IAzureFunctionDemoWebPartProps> {

private functionUrl: string = "https://spfx-demo-functions.azurewebsites.net/api/GetEmployeeData";

private callSecureAzureFunction(): void {
const resultContainer: HTMLElement = document.getElementById("resultContainer");

this.context.aadHttpClientFactory
.getClient("https://spfx-demo-functions.azurewebsites.net")
.then((client: AadHttpClient): void => {
client
.get(this.functionUrl, AadHttpClient.configurations.v1)
.then((response: HttpClientResponse): Promise<any> => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then((data: any): void => {
resultContainer.innerText = data.message;
})
.catch((error: any): void => {
resultContainer.innerText = `Error: ${error.message}`;
});
});
}

public render(): void {
this.domElement.innerHTML = `
<div>
<h2>Secure Azure Function Demo</h2>
<button id="callFunctionBtn">Call Secured Function</button>
<div id="resultContainer" style="margin-top: 10px;"></div>
</div>
`;

document.getElementById("callFunctionBtn").onclick = this.callSecureAzureFunction.bind(this);
}
}

Notice how I pass the root domain (https://spfx-demo-functions.azurewebsites.net) to getClient() â€” not the full function path. The AadHttpClient uses that to fetch the right token, then you use the full URL for the actual .get() or .post() call.

Step 5: Deploy and Approve Permissions

Package your solution:

heft test --clean --production
heft package-solution --production

Upload the .sppkg file to your SharePoint App Catalog. When you do, you’ll see a prompt about API permissions.

Then go to SharePoint Admin Center â†’ Advanced â†’ API access. You’ll see a pending request for your function. Click Approve.

Without this approval step, the web part can’t get an access token, and every call will fail with a 403.

Method Comparison at a Glance

MethodHttpClient (Anonymous)AadHttpClient (Secured)
Auth requiredNoYes — Azure AD token
Setup complexityLowMedium
Best forQuick prototypes, internal tools with no sensitive dataProduction apps, any function with sensitive logic
Secrets needed in codeNoNo
Admin approval neededNoYes — SharePoint API access page
SPFx version neededAnyv1.4.1 and above

Common Issues and How to Fix Them

Getting a CORS error?

Double-check that your SharePoint tenant domain is added under CORS in your Function App. Also make sure you didn’t accidentally add a trailing slash — https://tenant.sharepoint.com not https://tenant.sharepoint.com/.

Getting 401 Unauthorized with AadHttpClient?

The most common cause is that the API permission request hasn’t been approved yet in SharePoint Admin Center. Check there first.

Getting a 403 Forbidden?

Your permission was probably denied, or the scope name doesn’t exactly match what you defined in the Azure AD app registration. Check both places.

Function URL works in browser but not in SPFx?

That’s CORS again. Also check that your function’s Authorization Level is set correctly — if it’s set to Function level auth, you’ll need to pass a function key in the URL, which doesn’t mix well with the AadHttpClient approach.

A Few Tips Before You Ship

  • Version your API routes â€” use /api/v1/MyFunction instead of /api/MyFunction. When you change the logic later, you won’t break deployed web parts across all your sites.
  • Connect to Application Insights â€” you want to know if your function is failing silently in production. Link it from the Function App settings.
  • Keep response payloads small â€” SharePoint pages are already heavy. Don’t return a 5MB JSON blob when you only need 10 fields. Filter on the server side.
  • Use async/await instead of .then() chains if you’re on modern TypeScript — the code reads much cleaner.
  • Never hardcode function keys in SPFx code â€” they’ll be visible in the browser. If you need key-based auth, store the key in Azure Key Vault and access it from inside the function.

Conclusion

I hope you found this guide helpful and now have a clear understanding of how to call an Azure Function from an SPFx web part.

In this article, we started by creating an HTTP-triggered Azure Function, configured CORS for anonymous access, and learned how to call it using HttpClient. We then took it a step further by securing the Azure Function with Microsoft Entra ID (Azure AD), exposing an API scope, requesting permissions in the SPFx solution, and using AadHttpClient to make authenticated API calls. Finally, we compared both approaches so you can decide which one best fits your project.

As a general guideline, use HttpClient when your Azure Function is publicly accessible and doesn’t require authentication. If your function exposes sensitive data or business logic, securing it with Microsoft Entra ID and using AadHttpClient is the recommended approach.

I hope this walkthrough gives you a solid starting point the next time you need to integrate an Azure Function with an SPFx solution.

Also, you may like:

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Live Webinar

Create a SharePoint List & Columns from Excel Using Power Automate

Learn how to automatically create a SharePoint Online list and all its columns from an Excel file using Power Automate—without using any Premium connectors..

📅 4th Aug 2026 – 10:00 AM EST | 7:30 PM IST

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App