PnPjs in SPFx: The Default Data Layer for AI-Generated Web Parts

Ask a coding agent to show items from a SharePoint list. It can return a web part that works on a small list, yet fetches fields nobody displays, makes the request during render, and shows a blank panel when the request fails. Swapping the client for PnPjs doesn’t fix any of those problems by itself. The value in the SPFx development skill is that it tells the agent what to do around the request, too.

This is the data-access companion to Part 6’s Fluent UI guidance. That article explains what a web part should show while data is loading, missing, or unavailable. This one explains where the data call belongs, how much it should fetch, and what changes when the call goes to Microsoft Graph instead of SharePoint.

PnPjs Is the Skill’s Default, Not an SPFx Requirement

The shipped pnpjs.md reference tells the agent to start with PnPjs for SharePoint and Microsoft Graph data operations. It also names two exceptions: use SPHttpClient or MSGraphClientV3 if the user explicitly requires it or the project can’t add the dependency. Those are supported SPFx clients, not inherently bad code. A client choice made to comply with a project’s dependency policy is different from a client choice the agent made without inspecting the project.

The SPFx development skill is still in preview and installed manually. It isn’t bundled just because you installed the latest SPFx generator. The examples below use SPFx 1.24.1 as a concrete baseline, not a requirement for using the skill.

Pin the Package You Actually Use

For the list-read example, install @pnp/sp only. Add @pnp/graph if you also implement the optional profile lookup.

npm install --save-exact @pnp/sp@4.23.0
npm install --save-exact @pnp/graph@4.23.0

Both PnPjs packages were at 4.23.0 when this article was updated on November 18, 2026. That doesn’t make this pin right for every project. Check the existing package.json, lockfile, and TypeScript configuration before introducing or upgrading a dependency. Microsoft’s SPFx compatibility matrix lists React 18.3.1 for SPFx 1.24.1 and recommends Node.js 26 LTS for a new 1.24 environment. An existing solution may be on a different supported stack. As in Part 4’s upgrade playbook, inspect the project first instead of treating “latest” as a target.

Keep the Data Client Out of React Render

Put the query in a service. This one assumes the current SharePoint web has a list named Projects, and that the signed-in user can read it. The side-effect imports enable only the PnPjs features the example uses.

import type { WebPartContext } from "@microsoft/sp-webpart-base";
import { spfi, SPFx as spSPFx } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";
export class ProjectsService {
private readonly _sp: ReturnType<typeof spfi>;
public constructor(context: WebPartContext) {
this._sp = spfi().using(spSPFx(context));
}
public getProjects(): Promise<{ Id: number; Title: string }[]> {
return this._sp.web.lists.getByTitle("Projects").items.select("Id", "Title").top(50)();
}
}

Import ProjectsService into the web part and add the field and initialization to the existing class. If it already has an onInit(), keep its other initialization steps.

private _projects!: ProjectsService;
protected async onInit(): Promise<void> {
await super.onInit();
this._projects = new ProjectsService(this.context);
}

Pass the service or a load function into the React component. Call it from an effect or an event handler, not while calculating the render output. Show loading, empty, and error states separately: a request denied by SharePoint is not the same thing as an empty list.

A Bounded Read Is Not a Paging Strategy

.select("Id", "Title") asks for the two fields the view needs. .top(50)() asks for up to 50 items in a single query; it doesn’t follow later pages or guarantee which items are returned first. If the interface promises the newest items, specify an order. If users need to browse beyond the initial result, design for paging rather than fetching the entire list up front.

PnPjs v4 supports async iteration for list paging. When used on the iterator, .top() specifies a page size, not a total item limit. Put an explicit stopping condition on a bounded operation. Neither .top() nor paging fixes a query that runs into SharePoint’s list view threshold. For a large-list feature, plan selective filters and indexes around what the UI actually needs to retrieve.

Microsoft Graph Uses a Separate Client and Permission

If the web part also needs the signed-in user’s Microsoft Graph profile, use the SPFx behavior from @pnp/graph, not the one from @pnp/sp. Initialize it once with the same web part context and retain it if the feature makes repeated calls. These imports and statements belong in the Graph helper, not in React render.

import { graphfi, SPFx as graphSPFx } from "@pnp/graph";
import "@pnp/graph/users";
// Inside the Graph helper, with the web part context available:
const graph = graphfi().using(graphSPFx(context));
const me = await graph.me();

For Microsoft Graph GET /me, the least-privileged delegated permission for a work or school account is User.Read. If the applicable SPFx principal already has the required scope, don’t assume the team needs a new approval. If it doesn’t, declare the missing scope under solution.webApiPermissionRequests in config/package-solution.json. An authorized admin reviews the resulting request under SharePoint admin center → API access.

{
"webApiPermissionRequests": [
{ "resource": "Microsoft Graph", "scope": "User.Read" }
]
}

That JSON is a fragment of the solution object, not a replacement for the existing configuration. A successful build doesn’t establish that the tenant granted the scope. And Graph consent doesn’t give the user access to a SharePoint list: the calls run under separate permission checks. This SPFx example is delegated, not app-only. See Microsoft’s SPFx Graph walkthrough for the approval flow.

Review the Data Layer Before You Approve the PR

  • Dependency: Did the agent use the team’s compatible PnPjs version and install only the packages it needs? If it used a different client, is the reason documented?
  • Lifecycle: Is the client retained once per web part instance, and are requests kept out of render?
  • Query: Does the request select only the fields it needs and match the UI’s paging and ordering behavior?
  • Operations: Are errors visible, and has the team identified any required Graph approval before deployment?

The SharePoint and Graph client patterns compiled and packaged in a scaffolded SPFx 1.24.1 project with PnPjs 4.23.0. That was a build check, not a test of tenant consent, list access, or runtime behavior.

What’s Next

This completes the four reference-file walkthroughs introduced in Part 1. Like Part 7’s Fluent UI proposals, Part 9 will be a separate companion: proposed rules for paging, retry behavior, batch failures, and permission review, not features the skill already ships.

Leave a Reply