typescriptsharepoint-onlinespfxpnp-jsspfx-extension

How to configure a spfx extension at runtime like ENV vars?


If i write for example a node express app, i have the opportunity to pass some env vars from the server configuration.

Is there an opportunity in SharePoint Online also? As SharePoint Online is a managed service, there's imho no way to do so.

Is there possibly a workaround?

I stuck at creating any idea regarding this problem.

cheers Thomas


Solution

  • Just as an option, you can use property bag (like, site property bag) to define custom properties for a site, and then get them from your SPFx web part. You have property bags for many things in SharePoint, including tenant, site, list, etc.

    To set a property bag key/value for a site (powershell):

    Connect-PnPOnline -Url https://<yourdomain>.sharepoint.com/sites/<yoursite>
    Set-PnPPropertyBagValue -Key MYKEY -Value MYVALUE
    

    To get this "site" value from an SPFx web part, you can use the allProperties API (somewhere in your web part initialization):

    const propertyBag = await sp.web.allProperties.get();
    const value = propertyBag.MYKEY;
    
    console.log(value) // logs "MYVALUE"
    

    The same code if you are not using pnpjs:

    // context = <web part context>
    const apiUrl = `${context.pageContext.web.absoluteUrl}/_api/web/allProperties`;
    const rsp = await context.spHttpClient.get(apiUrl, SPHttpClient.configurations.v1);
    const propertyBag = await rsp.json();
    const value = propertyBag.MYKEY;
    

    Alternatively, you can just put the .env file (to site assets for example) and then read it from your SPFx web part.

    Not sure if this is common practice in any way (probably not), but just to give some options.