Method 1: Node.js Crypto Module
In Node.js applications, use the native `crypto.randomBytes()` API. Never use `Math.random()` or third-party random number packages that lack cryptographic auditing.
Method 2: Linux & macOS CLI (OpenSSL)
OpenSSL is universally installed on modern Unix servers and provides an immediate, foolproof command for `.env` initialization:
Method 3: Python secrets Module
Python 3.6+ includes the `secrets` standard library, designed specifically for cryptographic keys and authentication tokens.
Frequently Asked Questions
Why should I never use Math.random() for secrets?
Math.random() is a pseudo-random number generator designed for speed, not security. Its internal state can be fully reverse-engineered from just a few observed outputs.
Should I hardcode the generated secret in my source files?
Never. Secrets must always be injected through environment variables (.env) or a secret manager (AWS Secrets Manager, HashiCorp Vault).