HMAC Auth Express provides middleware for Express applications to implement HMAC (Hash-based Message Authentication Code) authentication. It is currently at version 9.0.0 and demonstrates an active development cadence with regular updates. Key differentiators include zero runtime dependencies (only Express as a peer dependency), timing-safe comparisons, 100% code coverage, support for all standard hash algorithms, and built-in replay attack prevention. The library also features flexible secret management, allowing for static secrets or dynamic resolution via an async function. It ships with full TypeScript type definitions, enhancing developer experience and ensuring type safety in modern JavaScript projects.
npm install hmac-auth-expressVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates basic HMAC middleware registration, proper ordering with `express.json()`, and a custom error handler for authentication failures.
Review how HMAC signatures are generated on the client-side, especially if request bodies or query parameters contain arrays. Ensure consistent array serialization/ordering between client and server for HMAC generation.
Ensure `app.use(express.json());` (or similar body parsers) is declared before `app.use(HMAC(...));` in your Express application setup.
Verify client-side HMAC header construction matches the expected format outlined in the documentation, including the identifier, UNIX timestamp, and the calculated hash signature separated by a colon.
Implement custom error handling middleware in Express to catch `AuthError` instances or errors with the code `ERR_HMAC_AUTH_INVALID` and return appropriate HTTP status codes (e.g., 401 Unauthorized) and messages.
Provide a string literal for your secret (e.g., `HMAC('your-secret')`) or a function that returns the secret (e.g., `HMAC((req) => process.env.HMAC_SECRET_KEY)`).Ensure the client-generated timestamp is a valid UNIX epoch timestamp (milliseconds) and that it is within the acceptable time window configured in the `HMAC` options (`maxInterval`, `minInterval`). Adjust client's system clock or server's options if time skew is the issue.
Verify that the client is generating the HMAC signature correctly, using the same secret, algorithm, and canonicalization rules (e.g., body parsing, array ordering) as the server. Common causes include mismatched secrets, incorrect body serialization, or differences in the `algorithm` option.