How To Apply Header While Using PnP In SPFx

Introduction

In this blog, we will learn how can we apply the header while using PnP in SPFx web parts.

When we use the fetch or ajax requests in SPFx, we have option to add the header to the Rest API requests we are using, but when using PnP, there is no option to add the header while performing CRUD operations in SharePoint.

For example, while using fetch request to get the list items, we can add the header as given in below code snippet:

return fetch(APIUrl, {
    credentials: 'same-origin',
    headers: {
        'Accept': 'application/json;odata=verbose',
        'odata-version': ''
    }
}).then((res) => res.json()).then((result) => {
        return result.d.results;
    },
    (error) => {
        console.error('Error:', error);
    });

But, when we use the PnP to get the list items, we will use below code and we will not have option to add the headers:

 await web.lists.getByTitle('List Title').items.select("Title").then((response) => {  
    this.setState({ SiteTimeZoneOnly: response[0].TimeZone });  
 });  

How to add headers

Step 1

Go to the .ts file of your web part.

Step 2

Now, go to the onInit method.

Step 3

Now, we can add the header in onInit method as given in below code snippet:

 protected onInit(): Promise<void> {  
   return super.onInit().then(_ => {  
    // other init code may be present  
    sp.setup({  
     spfxContext: this.context,  
     sp: {  
      headers: {  
        "X-ClientTag": "********"  
      }  
     }  
    });  
   });  
  } 

Here we have added 'X-ClientTag' header. You can also add comma separated multiple headers as well as given in below code snippet.

sp.setup({  
     spfxContext: this.context,  
     sp: {  
      headers: {  
        "X-ClientTag": "********",  
        "Accept": "application/json;odata=verbose"  
      }  
     }  
    }); 

Now your header is added successfully.

You can verify the headers from Network tab of developer tool as shown in below screenshot:

Conclusion

This is how we can add header in SPFx while using PnP to perform SharePoint list/library operations.