logo hsb.horse
← Back to blog index

Blog

Requesting an IAM-Protected API Gateway from TypeScript

How to send a TypeScript request from local development to an API Gateway protected by IAM authentication using SigV4 from the AWS SDK for JavaScript.

Published:

When IAM authentication is enabled on API Gateway, requests must be signed.

This is a TypeScript implementation for sending IAM-authenticated requests from a local environment.

Environment

  • Runs from a local environment
  • Works on Node.js (or Bun)

Implementation

Use SignatureV4 from the AWS SDK for JavaScript to add a signature to the request.

import { fromIni } from "@aws-sdk/credential-providers";
import { SignatureV4 } from "@aws-sdk/signature-v4";
import { Sha256 } from "@aws-crypto/sha256-js";
import { HttpRequest } from "@aws-sdk/protocol-http";
const credentials = fromIni({ profile: "profile-name" });
const serviceName = "execute-api";
const options = {
url: "https://{id}.execute-api.ap-northeast-1.amazonaws.com/",
headers: {} as Record<string, string>,
};
const url = new URL(options.url);
const host = url.hostname;
const path = url.pathname;
const req = new HttpRequest({
headers: {
Host: host,
},
hostname: host,
method: "GET",
path: path,
});
const signer = new SignatureV4({
credentials,
region: "ap-northeast-1",
service: serviceName,
sha256: Sha256,
});
const signed = await signer.sign(req);
const response = await fetch(options.url, {
headers: {
...signed.headers,
Host: host,
},
});

Key Points

  1. Load credentials from an AWS profile with fromIni
  2. Build the request object with HttpRequest
  3. Sign the request with SignatureV4
  4. Send the request with fetch and the signed headers

Summary

Using SignatureV4 from the AWS SDK for JavaScript makes it straightforward to call an IAM-protected API Gateway from a local environment.

Because credentials are loaded from an AWS profile, there is no need to hardcode them in source code.