Here’s an article based on the “Getting Started with PnPjs” guide from the PnPjs documentation:
Getting Started with PnPjs in SharePoint Framework (SPFx)
The PnPjs library provides a rich set of tools for developers to work with SharePoint and Microsoft 365 services using JavaScript. It abstracts complex REST API operations into simple, reusable, and efficient methods that can significantly speed up your development process. In this article, we will guide you through how to set up and start using PnPjs in a SharePoint Framework (SPFx) solution.
What is PnPjs?
PnPjs is a collection of fluent JavaScript libraries designed for consuming SharePoint and Microsoft Graph APIs. It provides support for both SharePoint Online and SharePoint on-premises and can be used in client-side applications such as SPFx, Node.js, and plain JavaScript.
Why Use PnPjs?
- Simplified API calls: PnPjs abstracts the REST API into simpler, easy-to-use methods.
- Fluent Interface: It allows chaining of method calls for a more readable and fluid code structure.
- TypeScript Support: The library fully supports TypeScript, making it a perfect choice for SPFx projects.
Step-by-Step Guide to Getting Started with PnPjs
Step 1: Install the PnPjs Library
To use PnPjs in your SPFx project, you need to install the core libraries from the NPM registry. Run the following command in the root directory of your SPFx solution:
npm install @pnp/sp @pnp/graph --save
@pnp/spis the package that provides access to SharePoint functionalities.@pnp/graphis the package that allows you to work with Microsoft Graph API.
Step 2: Update SPFx Web Part for PnPjs Usage
Once the packages are installed, you need to configure your SPFx web part to make use of PnPjs. Start by importing the required modules into your web part.
Open your YourWebPart.ts file and add the following import statements:
import { sp } from "@pnp/sp/presets/all";
import "@pnp/graph/users";
Here, we are importing everything from the PnP SharePoint module (sp) and also enabling the use of Microsoft Graph for handling users (@pnp/graph/users).
Step 3: Initialize the PnP Context in SPFx
The next step is to ensure that the PnP library is aware of the SharePoint context in which the SPFx web part is running. This is essential for PnPjs to correctly authenticate and communicate with SharePoint APIs.
Add the following initialization code inside your web part’s onInit() method:
protected onInit(): Promise<void> {
return super.onInit().then(_ => {
sp.setup({
spfxContext: this.context
});
});
}
This ensures that PnPjs is configured with the current SPFx context, allowing it to authenticate and perform operations under the logged-in user’s credentials.
Step 4: Perform SharePoint Operations
Once PnPjs is set up, you can start performing operations. For example, retrieving items from a SharePoint list is as simple as the following:
sp.web.lists.getByTitle("Documents").items.get().then(items => {
console.log(items);
});
This retrieves all items from a list named “Documents” and logs them to the console.
Step 5: Using Microsoft Graph with PnPjs
PnPjs also supports the Microsoft Graph API, making it easy to access users, groups, and other Microsoft 365 services. To get a list of users from your organization, you can use:
import { graph } from "@pnp/graph";
graph.users.top(5).get().then(users => {
console.log(users);
});
This fetches the top 5 users in your tenant using Microsoft Graph.
Key Features of PnPjs
PnPjs offers a wide range of functionalities for SharePoint and Microsoft 365 developers. Some key features include:
Fluent API
PnPjs provides a fluent API, allowing for readable, chainable method calls. For example, you can retrieve a specific list, select fields, and filter results in one fluent call:
sp.web.lists.getByTitle("Documents").items.select("Title", "Modified").filter("Modified ge '2023-01-01'").get().then(items => {
console.log(items);
});
Error Handling
Error handling with PnPjs is easy and follows standard JavaScript promises. You can catch errors as follows:
sp.web.lists.getByTitle("Documents").items.get().then(items => {
console.log(items);
}).catch(error => {
console.error("Error retrieving items:", error);
});
Batching Requests
You can batch multiple requests together to reduce the number of API calls and improve performance:
const batch = sp.web.createBatch();
sp.web.lists.getByTitle("Documents").items.inBatch(batch).get().then(items => {
console.log("List Items:", items);
});
sp.web.get().inBatch(batch).then(web => {
console.log("Web Info:", web);
});
batch.execute().then(() => {
console.log("Batch executed");
});
Caching
PnPjs also supports caching for scenarios where frequent data access is required:
sp.web.lists.getByTitle("Documents").items.usingCaching().get().then(items => {
console.log("Cached items:", items);
});
Advanced Use Cases
CRUD Operations
PnPjs makes Create, Read, Update, and Delete (CRUD) operations straightforward.
- Create a new item:
sp.web.lists.getByTitle("Documents").items.add({
Title: "New Document"
}).then(response => {
console.log("Item added:", response);
});
- Update an item:
sp.web.lists.getByTitle("Documents").items.getById(1).update({
Title: "Updated Document"
}).then(response => {
console.log("Item updated:", response);
});
- Delete an item:
sp.web.lists.getByTitle("Documents").items.getById(1).delete().then(response => {
console.log("Item deleted:", response);
});
Retrieve Document Libraries
To retrieve all document libraries in a SharePoint site, you can use:
sp.web.lists.filter("BaseTemplate eq 101").get().then(libraries => {
console.log(libraries);
});
This query filters for lists with a BaseTemplate of 101, which corresponds to document libraries.
Best Practices for Using PnPjs
- Batch Your Requests: Always batch requests when performing multiple operations to reduce network traffic.
- Use Caching: Leverage the built-in caching mechanisms to minimize API calls and improve performance.
- Error Handling: Implement robust error handling to ensure your application gracefully handles API failures.
- Leverage Fluent API: Utilize the fluent API style to make your code more readable and maintainable.
- Keep Libraries Updated: Regularly update your PnPjs libraries to take advantage of the latest features and improvements.
Conclusion
PnPjs is a powerful and flexible tool for working with SharePoint and Microsoft 365 APIs. Its fluent, TypeScript-friendly API makes it an ideal choice for SPFx development, offering a simplified and efficient way to perform common SharePoint tasks such as CRUD operations, list management, and user access through Microsoft Graph.
By following the steps outlined in this guide, you can quickly integrate PnPjs into your SPFx web parts and take advantage of its powerful features to improve both development speed and application performance.
Summary of Key Commands
| Action | Command/Operation |
|---|---|
| Install PnPjs | npm install @pnp/sp @pnp/graph --save |
| Initialize PnP Context | sp.setup({ spfxContext: this.context }); |
| Retrieve List Items | sp.web.lists.getByTitle("Documents").items.get() |
| Add a List Item | sp.web.lists.getByTitle("Documents").items.add({ Title: ... }) |
| Update a List Item | sp.web.lists.getByTitle("Documents").items.getById(id).update({...}) |
| Delete a List Item | sp.web.lists.getByTitle("Documents").items.getById(id).delete() |
| Retrieve Top 5 Users (Graph API) | graph.users.top(5).get() |
| Batch Requests | sp.web.lists.inBatch(batch).get(); batch.execute(); |
By using PnPjs, you can streamline your SharePoint and Microsoft 365 development process, making your code more readable, efficient, and easier to maintain.

Leave a comment