2

With PnPJS, is there a way to check if a site collection exists given several URL?

Something like this:

import {Site} from '@pnp/sp';

const sitesToCheck = [
'myspsite.net/sites/sc1' // exists
'myspsite.net/sites/sc2' // doesn't exist
'myspsite.net/sites/sc3' // doesn't exist
] 
for( const siteUrl of siteToCheck){
   const site = new Site(siteUrl)
   const rootWeb = site.getRootWeb();
}

4 Answers 4

0

Now there is a direct support for this:

import { sp } from "@pnp/sp";

// Specify which site to verify
const siteUrl = "https://tenant.sharepoint.com/sites/subsite";
const exists = sp.site.exists(siteUrl);
console.log(exists);
4

You can check whether site collection exists or not as below:

1) Add the below import statement, we will be using the SPHttpClient provided by PnPJS to make a REST call to /_api/SP.Site.Exists endpoint to determine if a site collection exists or not

import { sp } from "@pnp/sp";
import { SPHttpClient } from "@pnp/sp";

2) Modify your code as below, I created a helper method check if site collection exists or not and also used the render method, you can change it as per your requirement.:

public fetchData(siteUrl: string) : Promise<any> {
    return new Promise(function (resolve, reject) {
      var client = new SPHttpClient();

      client.post("https://myspsite.net/_api/SP.Site.Exists", {
        body: JSON.stringify({
          url: siteUrl
        }),
        headers: {
          "accept": "application/json;",
        },
      }).then(d => {        
        d.json().then((v: any) => {
          resolve(v.value);
        })
      }).catch(d => {
        reject(d);
      });

    });
}

public async render() {

    var sitesToCheck = [
      'https://myspsite.net/sites/sc1',
      'https://myspsite.net/sites/sc2', 
      'https://myspsite.net/sites/sc3'
    ];

    for (var i = 0; i < sitesToCheck.length; i++) {
          await this.fetchData(sitesToCheck[i]).then(d => {
            if(d){
                console.log("Site collection " + sitesToCheck[i] + " exists");
            }else{
                console.log("Site collection " + sitesToCheck[i] + " doesnt exist");
            }
          });
    }
}
0
1

I guess you could do something like this. You could play around with the return, but I made a returnobject with the url you sent in, a boolean if it exists, and the status (200, 403 or 404)

import { sp, Web } from "@pnp/sp";

// Class for return onject
export class WebExistsObj {
    url: string;
    status: number;
    doesExists: boolean;
}

// Methof for checking the site
public async checkSiteExists(webUrl: string): Promise<WebExistsObj> {

    try {
        // Make new web from url    
        const web = new Web(webUrl);

        // Try to get web and only select Title
        const webWithTitle = await web.select('Title').get();

        // If web does exist make a return object and return
        if (webWithTitle.Title.length > 0) {
            const returnObj: WebExistsObj = {
                url: webUrl,
                doesExists: true,
                status: 200
            };
            return returnObj;
        }

    }
    catch (error) {

        // If status is 403 it does exist but you don't have permissions
        // If 404 it just doesn't exist
        const exists = error.status === 403 ? true : false;

        const returnObj: WebExistsObj = {
            url: webUrl,
            doesExists: exists,
            status: error.status
        };
        return returnObj;
    }
}

public async mainFunctionThatYouRun(): Promise<void> {
    // let's see if it exists
    const returnData = await checkSiteExists("https://<tenant>.sharepoint.com/sites/test3");

    console.log(returnData);
}
0

sp.site.exists(url) is great - thank you for noticing it. However there is currently bug in it: if current page's url (where pnp js code is executed) contains hashes then sp.site.exists(url) call results in 403 response. Looks like it parses parent url incorrectly in this case. As workaround you still need to use /_api/SP.Site.Exists API call for that (sp.site.exists uses the same API under the hood):

let promise = context.spHttpClient.post(context.pageContext.site.absoluteUrl + "/_api/SP.Site.Exists",
  SPHttpClient.configurations.v1, {
  headers: {
    "accept": "application/json;"
  },
  body: JSON.stringify({
    url: s.url
  })
}).then((response: SPHttpClientResponse) => {
  response.json().then((exists: any) => {
    if (exists.value) {
      // site exists
    } else {
      // site doesn't exist
    }
  });
});

Your Answer

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

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