Use this guide when your code contains passwords, API keys, database connection strings or tokens, or before you share a project or deploy it. Have your project open, access to the services whose keys you use and your hosting platform's settings.
Step by step
Find every secret
Search your code for words like password, key, token, secret and connection strings. Check configuration files, scripts and test files too. List each secret and which service it belongs to.
Move secrets to environment variables
Replace each hard-coded value with code that reads an environment variable, such as DATABASE_URL or PAYMENT_API_KEY. For local development, put the values in a .env file loaded by your framework or a small library. Give variables clear, consistent names.
Stop secrets reaching Git
Add .env and any other secret files to .gitignore before committing. Create a .env.example file with the variable names but no real values, so others know what is needed. Check git status to confirm the real file is not staged.
Set secrets on your hosting platform
Add the same variables in your hosting or deployment platform's environment settings, not in the code. Use different keys for development and production where the service allows it. Limit who can view them.
Reduce what each key can do
Where possible, create keys with only the permissions the app needs, such as read-only access. Set spending or usage limits if the service offers them. This limits the damage if a key leaks.
Plan for leaks
If a secret is ever committed, shared or pasted somewhere public, revoke it and create a new one straight away. Removing it from the code afterwards is not enough, as copies may already exist. Check the service's logs for unexpected use.
Ready-to-use checklist
- All secrets found and listed
- Hard-coded values replaced with environment variables
- .env file created locally
- .env added to .gitignore
- .env.example with names only
- Secrets set on hosting platform
- Keys limited to needed permissions
- Leak response plan noted
Practical tips
- Never paste real keys into AI chats, forums or screenshots; use placeholders instead.
- Many Git hosting services can scan for exposed secrets, so turn this on if it is available.
- Rotate important keys periodically so an old leak cannot be used forever.
Common problems
My app cannot find the environment variable.
Check the variable name matches exactly, including capital letters, and that the .env file is loaded before the code reads it. Restart your development server after changing environment variables.
My secret is already in old Git commits.
Revoke the secret and issue a new one first, as that removes the risk. Cleaning Git history is optional afterwards and needs care on shared repositories.
The deployed app works locally but fails online.
The hosting platform probably does not have the variables set. Add each variable from your .env.example in the platform's settings and redeploy.