Digest Fetch

3.1.1 · active · verified Wed Apr 22

digest-fetch is a JavaScript/TypeScript library that provides digest and basic HTTP authentication capabilities for both the standard `fetch` API and `node-fetch` in Node.js environments. The current stable version is 3.1.1. This library distinguishes itself by strictly adhering to RFC2069, RFC2617, and RFC7616 for digest access authentication, supporting various algorithms like MD5, SHA-256, and SHA-512-256, including their session variants. It primarily acts as a plugin, wrapping the `fetch` function to handle the authentication challenge-response cycle seamlessly. Major version 3.x transitioned the package to an ES module, requiring changes in project configuration for both JavaScript and TypeScript users. It allows for customizable options such as algorithm, status codes for failure, and cnonce size, and can also be configured to perform basic HTTP authentication.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `digest-fetch` for digest authentication, create a `DigestClient`, and make an authenticated request in a TypeScript Node.js environment.

import DigestClient from 'digest-fetch';
import fetch from 'node-fetch'; // Required for Node.js environments

// Ensure node-fetch is globally available for DigestClient
// @ts-ignore - this is a common pattern for polyfilling fetch
globalThis.fetch = fetch;

async function authenticateAndFetch() {
  // Replace with actual credentials and URL
  const username = process.env.DIGEST_USER ?? 'testuser';
  const password = process.env.DIGEST_PASS ?? 'testpassword';
  const url = 'http://httpbin.org/digest-auth/auth/testuser/testpassword/MD5'; 

  // Create a DigestClient instance
  const client = new DigestClient(username, password, { algorithm: 'MD5' });

  try {
    // Make a request using the client's fetch method
    const response = await client.fetch(url, { method: 'GET' });

    if (!response.ok) {
      console.error(`HTTP error! status: ${response.status}`);
      const errorText = await response.text();
      console.error('Error details:', errorText);
      return;
    }

    const data = await response.json();
    console.log('Successfully authenticated and fetched data:');
    console.dir(data);
  } catch (error) {
    console.error('An error occurred:', error);
  }
}

authenticateAndFetch();

view raw JSON →