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:
- Create an HTTP-triggered Azure Function
- Configure CORS on it
- Build an SPFx web part
- 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:
- Click + Create a resource → search for Function App → click Create
- 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
- Click through to Review + Create → Create

Give it a minute or two to deploy.
Step 2: Create an HTTP-Triggered Function
Once your Function App is ready:
- Go into your Function App → click Functions in the left menu → + Add
- Select HTTP trigger as the template

- Give it a name, like
GetEmployeeData - Set the Authorization level to Anonymous for now (we’ll change this for the secure method)
- Click Create

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."
}
};
}
};

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

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.
- In your Function App, click CORS in the left navigation
- Add the following origins:
https://yourtenant.sharepoint.com(replace with your actual SharePoint domain)https://localhost:4321(for local SPFx workbench testing)
- Click Save

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)

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.

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:
- Go to Azure Portal → Azure Active Directory → App registrations → + New registration
- Give it a name like
SPFx-AzureFunction-API - Set the Redirect URI to Web →
https://spfx-demo-functions.azurewebsites.net/.auth/login/aad/callback - Click Register

- Go to Expose an API → click Add a scope
- Set the Application ID URI (Azure will suggest one — accept it)
- Add a scope like
user_impersonation, set admin consent required, and save

Copy the Application (client) ID — you’ll need it.
Step 2: Enable Azure AD Auth on the Function App
- In your Function App → click Authentication in the left menu
- Click Add identity provider
- Configure the following:
| Setting | Value |
|---|---|
| Identity provider | Microsoft |
| Tenant | Workforce configuration (current tenant) |
| App registration | Pick an existing app registration in this directory |
| App registration | SPFx-AzureFunction-API |
| Client application requirement | Allow requests from any application |
| Restrict access | Require authentication |
| Unauthenticated requests | HTTP 401 Unauthorized |

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
| Method | HttpClient (Anonymous) | AadHttpClient (Secured) |
|---|---|---|
| Auth required | No | Yes — Azure AD token |
| Setup complexity | Low | Medium |
| Best for | Quick prototypes, internal tools with no sensitive data | Production apps, any function with sensitive logic |
| Secrets needed in code | No | No |
| Admin approval needed | No | Yes — SharePoint API access page |
| SPFx version needed | Any | v1.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/MyFunctioninstead 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:
- SPFx Web Part Audience Targeting: Show Content to the Right People
- SharePoint Framework (SPFx) Form Validation
- SPFx Environment Variables
- Customize SharePoint List Command Bar Download Button Using SPFx Extension

Hey! I’m Bijay Kumar, founder of SPGuides.com and a Microsoft Business Applications MVP (Power Automate, Power Apps). I launched this site in 2020 because I truly enjoy working with SharePoint, Power Platform, and SharePoint Framework (SPFx), and wanted to share that passion through step-by-step tutorials, guides, and training videos. My mission is to help you learn these technologies so you can utilize SharePoint, enhance productivity, and potentially build business solutions along the way.