What is aws4fetch?
The aws4fetch npm package is a utility for making HTTP requests to AWS services with AWS Signature Version 4 signing. It simplifies the process of signing requests to AWS services, allowing developers to interact with AWS APIs securely and efficiently.
What are aws4fetch's main functionalities?
Signing HTTP Requests
This feature allows you to sign HTTP requests to AWS services using AWS Signature Version 4. The code sample demonstrates how to create an instance of AwsClient with your AWS credentials and make a signed request to an AWS service endpoint.
const { AwsClient } = require('aws4fetch');
const aws = new AwsClient({
accessKeyId: 'your-access-key-id',
secretAccessKey: 'your-secret-access-key',
sessionToken: 'your-session-token' // optional
});
const response = await aws.fetch('https://your-service.amazonaws.com/your-endpoint');
const data = await response.json();
console.log(data);
Customizing Request Options
This feature allows you to customize the HTTP request options such as method, headers, and body. The code sample shows how to make a POST request with custom headers and a JSON body to an AWS service endpoint.
const { AwsClient } = require('aws4fetch');
const aws = new AwsClient({
accessKeyId: 'your-access-key-id',
secretAccessKey: 'your-secret-access-key'
});
const response = await aws.fetch('https://your-service.amazonaws.com/your-endpoint', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key: 'value' })
});
const data = await response.json();
console.log(data);
Other packages similar to aws4fetch
aws-sdk
The aws-sdk package is the official AWS SDK for JavaScript, which provides a comprehensive set of tools for interacting with AWS services. It includes built-in support for request signing, similar to aws4fetch, but also offers a wide range of additional features such as service-specific clients, higher-level abstractions, and more extensive configuration options.
axios
While axios is a general-purpose HTTP client for Node.js and the browser, it can be used in conjunction with aws4 to sign requests to AWS services. Unlike aws4fetch, axios does not natively support AWS request signing, but it offers more flexibility and features for general HTTP request handling.
request
The request package is another popular HTTP client for Node.js that can be used with aws4 for signing AWS requests. Although request is now deprecated, it was widely used for making HTTP requests and could be extended with aws4 for AWS-specific use cases, similar to aws4fetch.
aws4fetch
A compact (6.4kb minified, 2.5kb gzipped) AWS client for environments that support
fetch
and
SubtleCrypto
– that is, modern web browsers and
JS platforms like Cloudflare Workers. Also retries
requests with an exponential backoff with full jitter
strategy by default.
Example
import { AwsClient } from 'aws4fetch'
const aws = new AwsClient({ accessKeyId: MY_ACCESS_KEY, secretAccessKey: MY_SECRET_KEY })
const LAMBDA_FN_API = 'https://lambda.us-east-1.amazonaws.com/2015-03-31/functions'
async function invokeMyLambda(event) {
const res = await aws.fetch(`${LAMBDA_FN_API}/my-lambda/invocations`, { body: JSON.stringify(event) })
return res.json()
}
invokeMyLambda({my: 'event'}).then(json => console.log(json))
You can see a more detailed example, a Cloudflare Worker script you can use as
a replacement for API Gateway, in the example
directory.
API
aws4fetch
exports two classes: AwsClient
and AwsV4Signer
new AwsClient(options)
You can use the same instance of AwsClient
for all your service calls as the service and region will be determined
at fetch time – or you can create separate instances if you have different needs, eg no retrying for some service.
import { AwsClient } from 'aws4fetch'
const aws = new AwsClient({
accessKeyId,
secretAccessKey,
sessionToken,
service,
region,
cache,
retries,
initRetryMs,
})
Promise<Response> aws.fetch(input[, init])
Has the same signature as the global fetch function
import { AwsClient } from 'aws4fetch'
const aws = new AwsClient(opts)
async function doFetch() {
const response = await aws.fetch(url, {
method,
headers,
body,
aws: {
signQuery,
accessKeyId,
secretAccessKey,
sessionToken,
service,
region,
cache,
datetime,
appendSessionToken,
allHeaders,
singleEncode,
},
})
console.log(await response.json())
}
NB: Due to the way bodies are handled in Request
instances, it's faster to invoke the function as above – using a URL as the input
argument and passing the body
in the init
argument – instead of the form of
invocation that uses a Request
object directly as input
.
If you don't know which URL to call for the AWS service you want, the full list
of AWS endpoints can be found here:
https://docs.aws.amazon.com/general/latest/gr/rande.html
And the APIs are documented here: https://docs.aws.amazon.com/ (the REST APIs
are usually documented under "API Reference" for each service)
Promise<Request> aws.sign(input[, init])
Returns a Promise that resolves to an
AWS4
signed Request
–
has the same signature as fetch
. Use this to create a Request
you can send
using fetch()
yourself.
import { AwsClient } from 'aws4fetch'
const aws = new AwsClient(opts)
async function doFetch() {
const request = await aws.sign(url, {
method,
headers,
body,
aws: {
signQuery,
accessKeyId,
secretAccessKey,
sessionToken,
service,
region,
cache,
datetime,
appendSessionToken,
allHeaders,
singleEncode,
},
})
const response = await fetch(request)
console.log(await response.json())
}
new AwsV4Signer(options)
The underlying signing class for a request – use this if you just want to deal
with the raw AWS4 signed method/url/headers/body.
import { AwsV4Signer } from 'aws4fetch'
const signer = new AwsV4Signer({
url,
accessKeyId,
secretAccessKey,
sessionToken,
method,
headers,
body,
signQuery,
service,
region,
cache,
datetime,
appendSessionToken,
allHeaders,
singleEncode,
})
Promise<{ method, url, headers, body }> signer.sign()
Actually perform the signing of the request and return a Promise that resolves
to an object containing the signed method, url, headers and body.
method
will be a String
, url
will be an instance of URL
,
headers
will be an instance of Headers
and
body
will unchanged from the argument you supply to the constructor.
import { AwsV4Signer } from 'aws4fetch'
const signer = new AwsV4Signer(opts)
async function sign() {
const { method, url, headers, body } = await signer.sign()
console.log(method, url, [...headers], body)
}
Returns a Promise that resolves to the signed string to use in the
Authorization
header
Used by the sign()
method – you shouldn't need to access this directly unless you're constructing your own requests.
Promise<String> signer.signature()
Returns a Promise that resolves to the
hex signature
Used by the sign()
method – you shouldn't need to access this directly unless you're constructing your own requests.
Installation
With npm do:
npm install aws4fetch
Or you can also reference different formats straight from unpkg.com:
ES Modules:
https://unpkg.com/aws4fetch@1.0.5/dist/aws4fetch.esm.js
UMD:
https://unpkg.com/aws4fetch@1.0.5/dist/aws4fetch.umd.js
CommonJS:
https://unpkg.com/aws4fetch@1.0.5/dist/aws4fetch.cjs.js