Getting the URL of SharePoint Pages and Documents using PnPjs in SPFx webparts

While developing some SPFx webparts or extensions, we might need to find the full URLs of the SharePoint items we read. For example, if we are developing a custom Image Gallery, the SPFx webpart should read all the items from a Image library and also need the full URLs of the images. Similarly when we are showing the list if pages or documents, we might need the full URLs for the pages and documents.

FileRef and EncodedAbsUrl

SharePoint provides 2 internal fields which we can use to find the direct URL for a given resource (page, document, image etc.,)

The FileRef, provides a relative url of the resource, while EncodedAbsUrl provides the full absolute URL for the resource.

Below are the code snippets to read the URLs for pages, documents and images using the PnPjs in your SPFx solutions

import { sp } from "@pnp/sp";
import '@pnp/sp/webs';
import '@pnp/sp/items';
// Pages
const pages = await sp.web.lists.getByTitle("Site Pages")"Title, FileRef, EncodedAbsUrl").get()
const docs = await sp.web.lists.getByTitle("Documents")"Title, FileRef, EncodedAbsUrl").get()

const images = await sp.web.lists.getByTitle("Site Assets")"Title, FileRef, EncodedAbsUrl").get()

Here is the sample JSON response from these queries.