Generate a random JWT secret

Run this script on the terminal:

node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

This script will generate a random 64 bit ASCII string, e.g. that can be used for encrypting JWT tokens.

Let’s explain the magic:

  1. node -e tells Node.js to evaluate a script, in this case, a Javascript string
  2. crypto is the cryptographic module forming part of Node.js core. It is already installed as part of Node.js, no extra npm package is involved.
  3. randomBytes() is a function that generates cryptographically strong pseudo-random data. It will return a Buffer object.
  4. toString() is a method of the Buffer class that decodes the object to a string according to the specified character encoding, which, in this case, is hex, viz. hexadecimal.

Each of the 64 characters can be:

  • A numbers from 0 to 9
  • A character: A, B, C, D, E and F

There are codes in the ASCII table that will not be used, but the random results are perfect for JWT tokens nevertheless.