Skip to content

Generate HMAC headers - Nodejs

The document API uses HMAC for authentication. You must use your private key and public key to create an HMAC digest for a request and pass that as part of the Authorization header.

The python code below shows the function that can be used to generate the headers for such a request:

ts
function getAuthorizationHeaders(
  method: string,
  path: string
): Record<string, string> {
  const datetime = new Date().toUTCString();
  const payload = Buffer.from(
    `${method.toUpperCase()}\n${datetime}\n${path.toLowerCase()}`,
    "utf-8"
  );

  const digest = crypto
    .createHmac("SHA256", Buffer.from(process.env.UNOPDF_PRIVATE_KEY!, "utf-8"))
    .update(payload)
    .digest("base64");

  const urlsafe = digest
    .replace(/\+/g, "-")
    .replace(/\//g, "_")
    .replace(/=+$/, "");

  return {
    Accept: "application/json",
    Timestamp: datetime,
    Authorization: `SharedKey: ${process.env.UNOPDF_PUBLIC_KEY}:${urlsafe}`,
  };
}

See the Authentication guide for more information.

The example below shows a fully working example that calls the /v1/files endpoint using HMAC signing.

Code

ts
import dotenv from "dotenv";
dotenv.config();

import * as crypto from "node:crypto";
import { getError } from "./errorhandling";

const api_url = process.env.UNOPDF_API_URL;

// #region generate_headers
function getAuthorizationHeaders(
  method: string,
  path: string
): Record<string, string> {
  const datetime = new Date().toUTCString();
  const payload = Buffer.from(
    `${method.toUpperCase()}\n${datetime}\n${path.toLowerCase()}`,
    "utf-8"
  );

  const digest = crypto
    .createHmac("SHA256", Buffer.from(process.env.UNOPDF_PRIVATE_KEY!, "utf-8"))
    .update(payload)
    .digest("base64");

  const urlsafe = digest
    .replace(/\+/g, "-")
    .replace(/\//g, "_")
    .replace(/=+$/, "");

  return {
    Accept: "application/json",
    Timestamp: datetime,
    Authorization: `SharedKey: ${process.env.UNOPDF_PUBLIC_KEY}:${urlsafe}`,
  };
}
// #endregion generate_headers

async function listDocuments() {
  const path = "/v1/files";
  const url = `${api_url}${path}`;
  const method = "GET";
  const headers = getAuthorizationHeaders(method, path);

  const response = await fetch(url, {
    headers,
  });

  if (response.status !== 200) {
    const error = await getError(response);

    console.error(error);
    throw new Error(`Error "${error}" calling UnoPdf API "${method} ${url}".`);
  }

  return await response.json();
}

listDocuments().then(() => console.log("ok"));

Running the example

  • Download the rest - Generate HMAC headers - Nodejs project
  • Unzip the file to a directory rest-generate-hmac-nodejs.
    shell
    unzip rest-generate-hmac-nodejs.zip -d rest-generate-hmac-nodejs
  • Open a terminal and go to that directory
    shell
    cd rest-generate-hmac-nodejs
  • Install dependencies
    shell
    npm install
    shell
    yarn
  • Start the project
    shell
    npm run start
    shell
    yarn start