Request signature in Node.js

This article presents a sample implementation of a request signature in Node.js.

# Dependencies

This example uses only core dependecies from Node.js: crypto and url.

# Example

The following simple example implements the algorithm described in the Request signature guide. The most important thing is to use the crypto module with the appropriate SHA256 algorithm and give the parameters in the right order: method, url, timestamp, body.

The method parameter should be provided in uppercase and the url should contain only the path from the URL, not the full URL address. The full URL address should be converted to /webhook?a=1.

If the algorithm works correctly, it should generate the same signature as the one given below: 56ac656c7f932c5b775be28949e90af9a2356eae2826539f10ab6526a0eec762 for the following parameters:

  • apiSecret=SECRET

  • method=POST

  • uri=http://demo.example.com/webhook?a=1

  • timestamp=1563276169752

  • body={a:1}

const crypto = require( 'crypto' );

function generateSignature( apiSecret, method, uri, timestamp, body ) {
    const url = new URL( uri );
    const path = url.pathname + url.search;

    const hmac = crypto.createHmac( 'SHA256', apiSecret );

    hmac.update( `${ method.toUpperCase() }${ path }${ timestamp }` );

    if ( body ) {
        hmac.update( Buffer.from( JSON.stringify( body ) ) );
    }

    return hmac.digest( 'hex' );
}

const expectedSignature = '56ac656c7f932c5b775be28949e90af9a2356eae2826539f10ab6526a0eec762';
const generatedSignature = generateSignature(
    'SECRET',
    'POST',
    'http://demo.example.com/webhook?a=1',
    1563276169752,
    { a: 1 }
);

console.log( expectedSignature === generatedSignature );

# Usage

Run:

node index.js