../courses.php
Node
NODE107
90
Secrets Must Stay Secret
Keep API keys, passwords, tokens, and private settings out of public code.
Where should Node keep secret values?
Secret values should stay on the server and usually be loaded from environment variables, not hard-coded into public source code.
Node often connects to databases, email systems, payment services, APIs, and admin tools.
Those systems usually require secrets: passwords, tokens, keys, and private URLs.
If secrets are committed into code, copied into frontend JavaScript, or shared by mistake, accounts can be abused.
A common Node pattern is to load secrets from environment variables.
The program can use the secret, but the secret does not belong inside the code file.
Reading a secret from the environment
// file: app.js
const apiKey = process.env.API_KEY;
if (!apiKey) {
console.error("Missing API_KEY environment variable.");
process.exit(1);
}
console.log("Secret was loaded safely.");
process.env gives Node access to environment variables.
API_KEY is the name of the secret setting.
The code checks whether the secret exists before continuing.
process.exit(1) stops the program when required configuration is missing.
The secret value is not printed or committed into the code.
Security
Secrets leaked into code can be stolen and abused.
Deployment
Different servers can use different secrets without changing code.
Separation
Code and private configuration should be separate.
Professional habit
Environment variables are normal in real Node deployments.
Hard-coded secret
const apiKey = "sk_live_private_key_here";
Environment variable
const apiKey = process.env.API_KEY;
Ask ChatGPT: "Which values in this Node code are secrets and should move to environment variables?" Then check every key, token, password, and private URL.
Create a Node file that reads process.env.API_KEY.
Check whether the value exists.
Print a safe message without printing the secret.
Run the file once without the variable.
Run it again with the variable set.
Committing secrets into Git.
Sending private keys to frontend browser code.
Printing secrets into logs.
Using the same secrets in development and production.
Ignoring missing environment variables until the app crashes later.
Keep Node secrets out of source code and load private configuration safely from environment variables.
Login - Jit4All
Login
Welcome back to Jit4All