How to generate a nonce in node.js?

João Pimentel Ferreira picture João Pimentel Ferreira · Apr 27, 2018 · Viewed 10k times · Source

I need to generate a nonce (number generated only once) to remove the CSP rule 'unsafe-inline' and all the trusted URLs for scripts, improving the CSP score. Thus I need to have in the HTML

<script nonce="{{{nonce}}}" src="http://example.com/file.js">

I know the nonce must be unique with a method of calculation almost impossible to predict, it should have at least 128 bits (hence 16 bytes), and be encoded in base64. Is therefore this correct for node.js?

const crypto = require('crypto');
let nonce = crypto.randomBytes(16).toString('base64');

Answer

Jo&#227;o Pimentel Ferreira picture João Pimentel Ferreira · Apr 29, 2018

Just to confirm that indeed this does work in NodeJS for CSP nonces

const crypto = require('crypto');
let nonce = crypto.randomBytes(16).toString('base64');