When working with JWT (JSON Web Tokens) in a Node.js application, your secret key plays a critical role in signing and verifying tokens.
A weak or predictable key can compromise your application’s security, so it’s best to generate it randomly.
Here’s how you can easily create a strong JWT secret key using Node.js:
Add Script to package.json
Open your package.json and inside the "scripts" section, add:
"scripts": {
"jwt-key": "node -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\""
}
Run the script
In your terminal run:
npm run jwt-key
You will get:
a47f7c20e4f9a87c6d0af6e6c8c4bc25d2a8e7c4a9f5c30f72db7d9a48f1c3d2
Copy that string into your .env
file.
If you use this often, you can even combine it with a direct write to .env so it replaces the JWT secret automatically:
"scripts": {
"jwt-key": "echo JWT_SECRET=$(node -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\") > .env"
}
This will overwrite .env
with the new secret each time.
Top comments (0)