Connecting to other sites with PnP JS 3.0.0

With the release of PnP JS 3.0.0, you’ll need to tweak a bit of code throughout your project. One particular case that has caused me issues in the migration is cases where you opened a Web or Site directly using it’s constructor such as the following:

const web = Web(myWebUrl);
const site = Site(mySiteUrl);

This syntax is no longer valid in PnP JS 3.0.0, however it won’t cause a build error. When your code executes a promise doesn’t get returned and your try / catch block won’t catch it. This leaves you trying to figure out why the rest of your code mysteriously stopped executing. I’ve already ran into this a couple of times in my migration effort.

This is not hard to fix with PnP JS 3.0.0 but the syntax is quite a bit different. First, get the imports you need:

import { SPFI, spfi, SPFx } from "@pnp/sp";
import { AssignFrom } from "@pnp/core";

To get a Site or Web object for another site, you’ll need to get a new SPFI object first. There are a few ways to do this but here is the one I went with. This assumes that you already established an SPFI object earlier for the current site and assigned it to this.sp.

const spSite = spfi(siteUrl).using(AssignFrom(this.sp.web));

Now that you have a new SPFI object tat has a Site object available to you such as:

await spSite.site.getContextInfo();
const webTitle = (await spSite.site.rootWeb()).Title;

That should get you going. Be sure and read the Getting Started guide for 3.0.0 to fully understand all of the changes when upgrading.

Published by coreyroth

Corey Roth is the Vice President of Product Strategy at AvePoint where he helps build the tyGraph product line for data analytics in Microsoft 365. Corey is an thirteen-time recipient of the Microsoft MVP award in Office Apps and Services. Corey has always focused on rapid adoption of new Microsoft technologies including Microsoft 365 and Azure.

Leave a comment