Building with AI is a blast. You describe what you want, the AI writes the code, and a few minutes later something works.
Then you want it to do something real. Send an email. Take a payment. Talk to ChatGPT or Claude. Every one of those services hands you the same thing to get started. An API key.
Here's where people get burned. You paste the key into the chat, say "make it work," and the AI drops it straight into your code. It works, so you move on. Now your secret key is sitting in a file that might end up on GitHub, inside your website, or in a folder you share.
I've built websites for more than 15 years, and I use AI tools every single day. If you're new to building this way, start with what vibe coding is and how to start. This post covers one habit that matters more than almost any other.
What counts as a secret
A secret is anything that proves who you are to a computer. If someone else gets it, they can act like you.
- API keys. Long strings that let your app use a service like OpenAI, Anthropic, Stripe or an email tool.
- Passwords. For your database, admin login or email account.
- Tokens. Like API keys, often used to connect apps to each other.
- Private keys and connection strings. The behind-the-scenes logins between your app and a database or server.
Anthropic, the company behind Claude, puts it well in its API key best practices. Your API key is a digital key to your account, and much like a credit card number, if someone gets it and uses it, they run up charges on your behalf.
Why AI tools put keys in your code
AI coding tools are built to get you to a working result. Give one a key and ask it to connect to a service, and the shortest path is pasting the key right into the file. It's just doing what you asked, the fastest way it knows.
The problem is that code travels. It gets saved to GitHub, copied, deployed and shared. Wherever the code goes, the key goes too.
GitHub's secret scanning docs say that when credentials like API keys and passwords are committed to repositories as hardcoded secrets, they become targets for unauthorized access. Anthropic says one of the most frequent causes of API key leaks is accidental exposure in public code repositories or third-party tools.
And it's not just a beginner mistake. OWASP, the nonprofit behind widely used web security guidance, notes in its Secrets Management Cheat Sheet that many organizations have API keys and database credentials hardcoded in their source code in plain text. The good news is the fix is simple.
How to keep API keys out of code in 8 steps
1. Never paste real keys into the chat
Don't paste your real API key into an AI chat to "help it understand." Anthropic's guidance says that when you put your key into third-party tools or platforms, you're giving that tool's developer access to your account. Tell the AI something like this instead.
I have an API key for this service. Don't put the key in the code. Read it from an environment variable called SERVICE_API_KEY and tell me where to add the real value myself.
The AI builds the plumbing. You fill in the secret yourself. For more on getting clean results, see how to write AI prompts that actually work.
2. Put secrets in a .env file
On your own computer, the usual home for secrets is a small file called .env. It's just a list of names and values.
OPENAI_API_KEY=your-key-goes-here
DATABASE_PASSWORD=your-password-goes-here
Your code reads the key by name instead of having it typed in. OpenAI's best practices for API key safety explain the payoff. With a consistent variable name like OPENAI_API_KEY, you can commit and share your code without the risk of exposing your key. Ask your AI tool to set this up.
3. Add .env to your .gitignore file
This is the step people skip. A .gitignore file tells Git which files to leave out when you save your project to GitHub. Anthropic says that if you store secrets locally in a .env file, you must add it to your ignore file, like .gitignore for Git, so you don't share it publicly by accident.
Your .gitignore should include lines like these.
.env
.env.local
One catch. Git's own documentation says .gitignore only applies to files Git isn't already tracking. If your .env file was already committed, adding it later won't remove it from your history. Treat that as a leak (see below).
4. Use environment variables on your hosting
Your .env file lives on your computer. When your app goes live, your host needs the keys too. Hosts like Vercel and Netlify have an environment variables settings page where you add each secret by name. Anthropic recommends using your cloud provider's secret management to pass the key to your app through an environment variable, and says to prefer encrypted secret storage over .env files in the cloud.
Ask the AI, "Which environment variables do I need to add on my host?" Then add them yourself in the dashboard.
5. Keep secret keys out of the browser
Some code runs on a server you control. Some runs in your visitor's browser, where anyone who knows where to look can see it.
OpenAI says to never deploy your key in client-side environments like browsers or mobile apps, because malicious users can take it and make requests on your behalf, which can lead to unexpected charges. Requests should go through your own backend server, where the key stays private.
Watch for names that make a value public on purpose. In Next.js, Vercel's docs explain, variables starting with NEXT_PUBLIC_ get built into the code sent to the browser. Never give a secret key that prefix.
If you're not sure, ask the AI. "Does any secret key end up in code that runs in the browser? If so, move it to a server-side function."
6. Turn on GitHub push protection and secret scanning
Push protection checks your code when you try to upload it and blocks the push if it spots a secret. According to GitHub's push protection docs, push protection for users is on by default and stops you from pushing secrets to public repositories. Push protection for a whole repository requires a GitHub feature called Secret Protection and is off by default, so an admin has to turn it on.
Secret scanning looks through your repository's entire Git history on all branches for things like API keys, passwords and tokens, and alerts you when it finds one. GitHub says it runs automatically for free on public repositories.
GitHub also works with service providers. Anthropic says that if a Claude API key shows up in a public GitHub repository, GitHub notifies Anthropic and Anthropic automatically deactivates the key.
If GitHub blocks your push, don't click past it. GitHub says to remove the sensitive information and try the push again, so move the secret to your .env file first.
7. Ask the AI to check for hardcoded secrets
Before anything goes live, make the AI do a security pass.
Search this whole project for hardcoded passwords, API keys, tokens or private keys. List every file and line where you find one, and show me how to move each one into an environment variable.
Then open the files it lists and confirm the keys are really gone. AI is a great second set of eyes, not a perfect one. More on that kind of review in what to test before you launch a website or web app.
8. Use limited keys and spending limits
Plan for the day something slips, and make each key as limited as you can.
- Use separate keys for separate jobs. Anthropic suggests different keys for development, testing and production, so if one is exposed you can shut off just that one.
- Give keys only the access they need. OWASP calls this the least privilege principle. OpenAI also lets you set permissions on individual API keys.
- Set expiration dates where offered. OpenAI says project keys can be created with an expiration date, and it strongly recommends a regular rotation process.
- Set spending limits. OpenAI recommends monthly spend limits with hard enforcement to help limit unexpected costs from a leaked key, and notes that spend alerts alone don't stop API traffic. Anthropic also points to spend and rate limits as a safeguard against leaked keys.
What to do if an API key leaks
If you think a key got out, don't panic, and don't start by deleting it from your code. Go in this order.
- Revoke or rotate the key first. Log in to the service, delete or roll the exposed key and create a new one. GitHub says to rotate the affected credential immediately.
- Put the new key in the right place. Add it to your .env file and your hosting environment variables, not the code, then redeploy.
- Check your usage. Look at the service's usage page for anything you didn't do. OpenAI and Anthropic both point to usage pages for this.
- Clean up the code and history if you need to. GitHub says you can also remove secrets from your Git history, but it's time-intensive and often unnecessary if you've already revoked the credential. Rewriting history has side effects, so follow GitHub's guide on removing sensitive data if you do it.
- Fix the cause. Add .env to .gitignore, turn on push protection, and ask your AI tool to scan for any other hardcoded secrets.
The order matters. Deleting the key from your code doesn't help if someone already copied it. Revoking it does.
Make it part of your rules
If you have a team, even a small one, make this a rule. Passwords and API keys never go into AI chats or code, only .env files and hosting settings. My post on how to write an AI policy for a small business puts passwords, API keys and logins in the red, never-goes-in category for exactly this reason.
Keeping secrets safe is part of the job you take on when you build, which is worth weighing in build vs. buy software. The same goes when you build an AI agent without coding, since those connections run on keys too.
Final thoughts
AI made building software fast. It didn't make secrets any less secret.
The habit is simple. Keep real keys out of the chat and the code. Use a .env file that's in your .gitignore, and hosting environment variables when you go live. Keep secret keys out of the browser, let GitHub catch mistakes, and give every key the smallest job and spending limit you can.
And if a key ever leaks, revoke it first and clean up second.
FAQ
How do I keep API keys out of my code?
Store them outside your code. On your computer, put them in a .env file listed in .gitignore. On your live site, add them as environment variables in your hosting dashboard. Your code reads each key by name instead of having it typed in.
Is it safe to paste my API key into an AI chat?
It's better not to. Anthropic says not to share your key in public forums, emails or support tickets, and warns that putting it into third-party tools gives that tool's developer access to your account. Ask the AI to read the key from an environment variable, then add the real value yourself.
Why does AI-generated code have API keys in it?
Usually because the AI was handed the key and took the shortest path to working code. Tell it up front to use environment variables, and ask it to scan for hardcoded secrets before you ship.
Is a .env file safe?
On your own computer, yes, as long as it's listed in .gitignore and never shared. In the cloud, Anthropic recommends encrypted secret storage from your provider over .env files.
What should I do if I accidentally pushed an API key to GitHub?
Revoke or rotate the key right away in the service that issued it, then put the new key in your .env file and hosting settings. GitHub says removing a secret from Git history is time-intensive and often unnecessary once the key is revoked. Then check your usage and turn on push protection.
Can I put an API key in front-end JavaScript?
Not a secret key. Code that runs in the browser can be seen by your visitors. OpenAI says never to deploy your key in browsers or mobile apps and to route requests through your own backend server.