How to generate HMAC-SHA256 in Node.js

Compute an HMAC-SHA256 message authentication code in Node.js for webhook signatures, API request signing, and understanding HS256 JWT internals. Use the browser HMAC Generator to compare digests while debugging, then implement crypto.createHmac with a strong shared secret and constant-time comparison on verify.

Last updated August 26, 2026

Steps

  1. 1

    Open the HMAC Generator, enter a test message and secret, and select SHA-256.

  2. 2

    Copy the hex digest — computation is client-side for safe local debugging.

  3. 3

    In Node.js, compute the same digest with crypto.createHmac and confirm it matches the tool.

  4. 4

    When verifying untrusted digests, use a constant-time compare (never == on hex strings alone).

  5. 5

    For production secrets, generate entropy with the JWT Secret Generator and store it outside source control.

Code Example

Node.js
const crypto = require('crypto');

const secret = process.env.HMAC_SECRET; // use a strong random secret
const message = 'webhook-body-or-signing-input';
const digest = crypto.createHmac('sha256', secret).update(message).digest('hex');

// Compare against the browser HMAC Generator when debugging.
// When verifying untrusted input, use timing-safe equality:
const expected = Buffer.from(digest, 'hex');
const provided = Buffer.from(incomingHex, 'hex');
crypto.timingSafeEqual(expected, provided);
Open HMAC Generator

Other languages

Related Articles

Frequently Asked Questions

What is HMAC-SHA256 used for?

HMAC authenticates a message with a shared secret. Common uses include webhook verification, API request signing, and the MAC step inside HS256 JWTs.

How do I verify an HMAC in Node.js?

Recompute the digest with crypto.createHmac over the exact same bytes the sender signed, then compare with a timing-safe equality helper. Mismatched encoding (hex vs Base64) is a frequent bug.

Is HMAC the same as hashing a password?

No. HMAC is fast and keyed. Password storage needs a slow KDF such as bcrypt, scrypt, or Argon2.

Is the browser HMAC Generator safe?

Yes for debugging — digests are computed locally. Do not paste live production secrets into shared or untrusted browsers.