Compact AWS Client for Modern JS

1.0.20 · active · verified Tue Apr 21

aws4fetch is a JavaScript library designed for signing AWS requests using the AWS Signature Version 4 process. It provides a compact client (6.4kb minified, 2.5kb gzipped) tailored for modern JavaScript environments that natively support the Web `fetch` API and `SubtleCrypto`. This makes it particularly well-suited for serverless edge computing platforms like Cloudflare Workers, as well as modern web browsers. The library is currently at version `1.0.20` and maintains an active release cadence, frequently adding support for new AWS features and refining existing functionality. A key differentiator is its built-in exponential backoff with full jitter retry strategy, enhancing the reliability of AWS interactions. Unlike traditional Node.js-centric AWS SDKs, `aws4fetch` leverages browser-native APIs, prioritizing minimalism and performance in environments where those APIs are readily available.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate `AwsClient` with credentials and use it to invoke an AWS Lambda function via the `fetch` API, handling potential errors.

import { AwsClient } from 'aws4fetch';

// In a real application, retrieve these from secure environment variables or a secrets manager.
// For demonstration, use placeholders or process.env.
const MY_ACCESS_KEY = process.env.AWS_ACCESS_KEY_ID ?? 'YOUR_AWS_ACCESS_KEY_ID';
const MY_SECRET_KEY = process.env.AWS_SECRET_ACCESS_KEY ?? 'YOUR_AWS_SECRET_ACCESS_KEY';
const MY_SESSION_TOKEN = process.env.AWS_SESSION_TOKEN ?? undefined; // Optional for temporary credentials

async function setupAndInvokeLambda() {
  if (!MY_ACCESS_KEY || !MY_SECRET_KEY) {
    console.error("AWS credentials are not set. Please provide MY_ACCESS_KEY and MY_SECRET_KEY.");
    return;
  }

  const aws = new AwsClient({
    accessKeyId: MY_ACCESS_KEY,
    secretAccessKey: MY_SECRET_KEY,
    sessionToken: MY_SESSION_TOKEN,
    region: 'us-east-1' // Explicitly set a region if known, or let aws4fetch parse it
  });

  // Example: Invoking an AWS Lambda function
  // Replace 'my-lambda' with your actual Lambda function name.
  // The API endpoint structure is standard for Lambda Invoke API.
  const LAMBDA_FN_API_BASE = 'https://lambda.us-east-1.amazonaws.com/2015-03-31/functions';
  const functionName = 'my-test-lambda'; // Replace with your Lambda function name
  const url = `${LAMBDA_FN_API_BASE}/${functionName}/invocations`;

  const eventPayload = {
    message: 'Hello from aws4fetch!',
    timestamp: new Date().toISOString()
  };

  try {
    console.log(`Invoking Lambda function: ${functionName} with payload:`, eventPayload);
    const res = await aws.fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(eventPayload)
    });

    if (res.ok) {
      const jsonResponse = await res.json();
      console.log('Lambda invocation successful:', jsonResponse);
      return jsonResponse;
    } else {
      const errorText = await res.text();
      console.error(`Lambda invocation failed with status ${res.status}:`, errorText);
      throw new Error(`Lambda invocation failed: ${res.status} ${errorText}`);
    }
  } catch (error) {
    console.error('Error during Lambda invocation:', error);
    throw error;
  }
}

// Call the async function
setupAndInvokeLambda().catch(err => console.error("Unhandled error:", err));

view raw JSON →