DEV Community

Guido Zambarda
Guido Zambarda

Posted on • Originally published at iamguidozam.blog on

Tenant settings with SPFx and PnP JS

Tenant settings are a useful way to define settings for an SPFx solution without the need to handle all the settings in the property pane, in this way you also don’t need to configure the web part again if you need to remove it. To achieve this result we’re using PnP JS.

I developed a sample solution with nothing more than a button that opens an URL defined in the tenant settings.

If no setting is defined the button will be disabled:

If the URL is defined in the settings the button will be enabled and, once clicked, will open a new tab with the specified URL:

The code

To start with the settings you need to import the PnP JS package, you can install it executing:

npm i @pnp/sp --save
Enter fullscreen mode Exit fullscreen mode

For this sample I created a SettingsService to handle the operation of reading from the tenant setting, to do so you need to specify the required imports:

import { PageContext } from "@microsoft/sp-page-context";
import { spfi, SPFI, SPFx } from "@pnp/sp";
import "@pnp/sp/appcatalog";
Enter fullscreen mode Exit fullscreen mode

In the constructor of the SettingsService we get the PageContext and instantiate the needed object to handle the settings:

public constructor(serviceScope: ServiceScope) {
 serviceScope.whenFinished(async () => {
  const pageContext: PageContext = serviceScope.consume(
        PageContext.serviceKey
    );
    this._sp = spfi().using(SPFx({ pageContext }));
 });
}
Enter fullscreen mode Exit fullscreen mode

Once that you have instantiated the this._sp object you can use it to get the tenant settings. In this sample I have an object saved to the tenant setting so I defined a Load function that returns the object:

private async Load(): Promise<Settings | undefined> {
 const appCatalog = await this._sp.getTenantAppCatalogWeb();

 const settings = await appCatalog.getStorageEntity(this.settingsKey);

 if (settings && settings.Value) {
    return JSON.parse(settings.Value);
 } else {
    return undefined;
 }
}
Enter fullscreen mode Exit fullscreen mode

With that you can now read your value!

Now that you know how to read a setting the next step is to set it, to do so you can can do it in SPFx using this._sp.setStorageEntity or use PnP PowerShell with the script:

# Connect to the admin portal
Connect-PnPOnline -Url "https://{your-domain}-admin.sharepoint.com" -Credentials: (Get-Credential)

# Set the target URL to the tenant property
Set-PnPStorageEntity -Key Sample:Settings -Value '{ "targetUrl": "{your-target-url}"}'
Enter fullscreen mode Exit fullscreen mode

NB: the Key value provided must be the same used with the getStorageEntity method.

You can find the code of the sample here.

Hope that helps!

Top comments (0)