npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

fastify-aws-sig4-auth

v0.0.1

Published

Protect Fastify routes with AWS Signature V4

Readme

fastify-aws-sig4-auth

Fastify plugin that verifies AWS Signature Version 4 on requests.

Use this to protect your API routes with the battle-tested and widely supported AWS signature algorithm.

You can use your favorite tool such as Postman to send signed requests for your app. In fact, this module has been primarily created to sign and call private APIs from Postman.

The only runtime dependency is mhart's excellent aws4 module.

Install

npm install fastify-aws-sig4-auth

Usage

Basic server-side syntax

import Fastify from "fastify";
import fastifyAwsSigV4 from "fastify-aws-sig4-auth";

const app = Fastify();

await app.register(fastifyAwsSigV4, {
  // Any string value will do, but you will have to supply the same
  // values to craft valid signature.
  region: "ukraine-kiev",
  service: "my-service",

  async getCredentials(accessKeyId) {
    // Actually query the database for your user
    return {
      accessKeyId,
      secretAccessKey: 'secret-access-key'
    };

    // In case the user is unknown:
    // return null;
  },
});

// Now the fastify instance is ready to do the auth.

// Example 1, handle a single route:
app.post(
  "/private",
  {
    preValidation: app.verifyAwsSigV4
  },

  async request => {
    console.log(`Successfully authenticated with ${request.accessKeyId}`);

    return {
      ok: true
    };
  }
);

// Example 2, handle all routes:
app.addHook("preHandler", app.verifyAwsSigV4);

app.post(
  "/private",

  async request => {
    console.log(`Successfully authenticated with ${request.accessKeyId}`);

    return {
      ok: true
    };
  }
);

Example

See example/. Or you can start right away:

cd example
npm install
node index.ts

And start sending signed POST and GET requests to http://localhost:3000/protected.

Call a protected route with fetch()

Sign the request before sending it. aws4fetch by the same author as aws4, creates a standard signed Request; the network call below is the native fetch():

npm install aws4fetch
import { AwsClient } from "aws4fetch";

const body = JSON.stringify({ hello: "world" });

const client = new AwsClient({
  accessKeyId: "AKIDEXAMPLE",
  secretAccessKey: "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY",
  // Must match the plugin configuration:
  region: "ukraine-kiev",
  service: "my-service"
});

const request = await client.sign("http://localhost:3000/private", {
  method: "POST",
  headers: { "content-type": "application/json" },
  body
});

// Now send as usual:
const response = await fetch(request);
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
console.log(await response.json());

The body passed to fetch() must be exactly the body that was signed, so absolutely do JSON.stringify() just once.

CORS considerations

Configure CORS to allow Authorization, Content-Type, X-Amz-Date and X-Amz-Content-Sha256 when calling a different origin. Use @fastify/cors.

Options

| Option | Required | Description | | --- | --- | --- | | region | Yes | Region required in the SigV4 credential scope | | service | Yes | Service required in the SigV4 credential scope | | getCredentials(accessKeyId, request) | Yes | Returns credentials for an enabled access key, or null when unknown. It may be async. | | maxClockSkewMs | No | Allowed clock difference from X-Amz-Date; defaults to a minute. | | unauthorizedResponseBody | No | What should we reply.send() in case we are serving a 401 response. Default: { message: "Unauthorized" } | | skipCaptureRawBody | No | See Body signing considerations below |

Temporary AWS credentials are deliberately not supported.

request properties

request.accessKeyId is populated in case of successful authentication.

Request requirements

Protected requests must use AWS4-HMAC-SHA256 and include:

  • Authorization with a SigV4 credential, signed-header list, and signature
  • Host in the signed-header list
  • X-Amz-Date matching the credential date scope

With skipCaptureRawBody: true, also:

  • X-Amz-Content-Sha256 containing the hexadecimal SHA-256 hash of the request body (see also Body signing considerations below)

The plugin responds with 401 { "message": "Unauthorized" } for invalid signatures, unknown keys, invalid payload hashes, malformed headers, and timestamps outside the configured skew. Credential-lookup failures produce 500 and are logged.

UNSIGNED-PAYLOAD intentionally rejected. AWS streaming payload signatures (STREAMING-AWS4-HMAC-SHA256-*) are not supported.

Body signing considerations

By default (skipCaptureRawBody: false) the raw request body is collected in memory in full and passed to aws4.RequestSigner for verification. This is a reasonable, "default" behavior. This way the body is captured twice: once for AWS verification, and once for parsing into request.body by Fastify.

For the vast majority of cases this is perfectly fine. However on a high load webserver it might be beneficial to NOT capture the raw body twice and instead rely on a supplied body signature. In this case set skipCaptureRawBody to true and send requests with the X-Amz-Content-Sha256 header populated. In this mode the plugin will NOT collect the request body, will NOT pass it to aws for verification and instead rely on checksum validation, which is 100% secure. The reason why this mode is not the default is that different software might sign the payload in a different ways and the safe default is to collect the body.

In order to check whether your client sends requests with checksum, use the example in example/ and try to send requests to the sample server to see whether they succeed.

This plugin calculates the SHA-256 payload checksum while Fastify reads the request stream.

This plugin is compatible with fastify-raw-body.

Development

npm install
npm run check
npm test
npm run build

The package is ESM-only.

eslint

You will need to install eslint-config-airbnb-extended, then force install typescript@6, @eslint/js and eslint@latest. Then run:

npx eslint src