Sometimes you want to restrict access to your PDFs so they aren’t publicly available on the internet. The easiest way to achieve this is with HTTP basic authentication(opens in a new tab).

If you try to load a PDF URL that’s protected by HTTP basic authentication, Nutrient will ask you for a username and password. To avoid entering these, you can fetch the PDF yourself, passing the credentials as an Authorization header. Once you’ve received the response, the load method accepts the content as an ArrayBuffer (try it in the Playground(opens in a new tab)):

async function loadProtectedPDF(url, username, password) {
// Base-64 encode your credentials and set them as an `Authorization` header.
const headers = new Headers();
const encodedCredentials = btoa(`${username}:${password}`);
headers.set("Authorization", `Basic ${encodedCredentials}`);
try {
// Fetch the PDF and read the response as an `ArrayBuffer`.
const pdfResponse = await fetch(url, { headers });
if (!pdfResponse.ok) {
throw new Error(`HTTP error: ${pdfResponse.status}`);
}
const document = await pdfResponse.arrayBuffer();
// Pass the `ArrayBuffer` as a PDF option instead of a URL.
const instance = await NutrientViewer.load({
container: "#pspdfkit",
document
});
console.log("Protected document loaded successfully");
return instance;
} catch (error) {
if (error.message.includes("401")) {
console.error("Authentication failed: Invalid credentials");
} else {
console.error("Failed to load protected document:", error.message);
}
throw error;
}
}