Restrict Access to PDFs with HTTP Basic Authentication

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.

If you try to load a PDF URL that’s protected by HTTP Basic authentication, PSPDFKit 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:

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}`);

  // Fetch the PDF and read the response as an `ArrayBuffer`.
  const pdfResponse = await fetch(url, { headers });
  const document = await pdfResponse.arrayBuffer();

  // Pass the `ArrayBuffer` as a PDF option instead of a URL.
  return PSPDFKit.load({ ...myOtherConfigOptions, document });
}