I am trying to update a file in document library from webpart, code is working fine for site collection but not working for subsite, getting below error message

Error: Error making HttpClient request in queryable [403]  ::> {"odata.error":{"code":"-2147024891, System.UnauthorizedAccessException","message":{"lang":"en-US","value":"Access denied."}}}

I am using pnp js, here is the code I am using

          const file = await _sp.web.getFileByUrl(fileUrl);
          try {
            await file.setContent(fileContent);
          } catch (error) {

Getting error in file.setContent

_sp is initialized in webpart's oninit method

public async onInit(): Promise<void> {
    await super.onInit();

getSP is coming from config file

var _sp: SPFI = null;

export const getSP = (context?: WebPartContext): SPFI => {
  if (_sp === null && context != null) {
    //You must add the @pnp/logging package to include the PnPLogging behavior it is no longer a peer dependency
    // The LogLevel set's at what level a message will be written to the console
    _sp = spfi().using(SPFx(context)).using(PnPLogging(LogLevel.Warning));
  return _sp;

file url is comin from query string.

Webpart is added to a page in site colection, which tries to read/set file content to a file in subsite.

  • It seems you don't have access on library in subsite Oct 4, 2022 at 12:23
  • @RajatSahani its admin user with full control
    – user4205
    Oct 4, 2022 at 14:05

1 Answer 1


I was able to find the root cause and fix the issue, root cause was I was using root web object to try updating a file in subsite, I have to use subsite web object, here is the fix I have used:

      try {
            await file.setContent(fileContent); //update the file content
          } catch (error) {
            try {
            console.log("trying new approach");
            const web = Web([_sp.web, siteURL]); //Initiate new web object, existing web will not work for subsite 
            const file2 = await web.getFileByUrl(fileUrl);
            await file2.setContent(fileContent);
            } catch (error) {

siteURL is the subsite's absolute url coming from querystring

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.