How to store API keys safely in a web or mobile app

Short answer
- Any key shipped inside a web page or phone app can be read by the people who use it. Only keys that the provider labels safe to publish belong there, such as Stripe’s pk_ keys and Supabase’s sb_publishable_ keys.
- Secret keys belong on a server, in your platform’s secrets store or an environment variable that the browser never sees. Your app calls your server and the server calls the API.
- Frontend “environment variables” are public. Vite, Next.js, Expo and Bolt all say that VITE_, NEXT_PUBLIC_, EXPO_PUBLIC_ and PUBLIC_ values end up in readable code.
- On the phone itself, login tokens go in Apple’s Keychain on iPhone, or on Android in storage protected by a key in the Android Keystore. Never in AsyncStorage or plain shared preferences.
- If a secret key leaks, revoke or rotate it first and tidy up the code second. Deleting the line from your code doesn’t stop the old key working.
An API key is a long string that tells a service “this request comes from my account”. Some keys only identify you. Others can spend your money, read every customer’s data or delete things.
The trouble starts when the second kind ends up where the public can reach it. That happens a lot with apps built in an afternoon with AI tools.
This piece is part of our app security guide, which covers the wider picture. Here I’m going deep on one question: where each kind of key should live, and how to check yours today. Every rule below comes from the provider’s own documentation or from OWASP, checked on 6 December 2026.
Is it safe to put an API key in your app’s code?
Only if the provider says that particular key is safe to publish. Everything else in your app’s code should be treated as readable by anyone.
A web app sends its JavaScript to every visitor. Lovable’s security guide puts it plainly: anyone can read the code that runs in a visitor’s browser.
Phone apps feel more sealed, but they can be unpacked too. The React Native docs say anything in your code can be read in plain text by anyone inspecting the app bundle.
Google’s Android security guidance says an attacker with reverse engineering tools can retrieve a hard-coded secret “very easily”. And Stripe warns that people unpack applications specifically to search for embedded keys.
The OWASP Mobile Top 10, the standard list of mobile app risks, puts improper credential usage at number 1 and says to avoid hardcoded credentials in code or config files.
So the useful question for each key is simple. Is this one meant to be public?
Which API keys are safe to expose and which must stay secret?
Each provider labels its own keys, and the labels are usually clear once you know where to look. Here are the keys I see most often in apps that come to us for help, with what each provider’s docs say today.
| Key | Safe in the app? | What the provider’s docs say |
|---|---|---|
| Stripe publishable key (pk_live_, pk_test_) | Yes | For Stripe.js, Elements and mobile SDKs; can’t create charges or read account data |
| Stripe secret key (sk_live_, sk_test_) | No | Unrestricted access to all Stripe APIs; Stripe recommends restricted keys instead |
| Stripe restricted key (rk_live_, rk_test_) | No | Server-side, with only the permissions you choose |
| Supabase publishable key (sb_publishable_, legacy anon) | Yes, with access rules on | Safe in a web page or mobile app; protection comes from row-level security |
| Supabase secret key (sb_secret_, legacy service_role) | No | Bypasses every row-level security policy; never in a browser, a shipped app or source control |
| Firebase API key | Yes | OK in code if the key is limited to Firebase services; access is controlled by Security Rules and App Check |
| Gemini Developer API key | No | Should never be in your code or config files |
| OpenAI API key | No | Never deploy it in browsers or mobile apps |
| Google Maps Platform key | Restrict it | Always add an app or website restriction and limit it to the APIs it uses |
Sources: Stripe API keys, Supabase API keys, Firebase API keys, OpenAI key safety, Google Maps security, all checked 6 December 2026.
Two rows trip people up. The Firebase key is public by design, and that’s fine, because the rules behind it do the protecting. If those rules are missing, a “safe” key still opens the door.
The Supabase publishable key works the same way. Supabase’s docs are clear that it’s fine to ship, but only because row-level security (rules attached to each database table saying who can read which rows) is meant to be switched on. The database rules section of our security guide covers that half of the story.
One detail I like: Supabase rejects a secret key sent from a browser with a 401 error. Its docs also say an attacker can still use that key from other tools, so the block catches mistakes in testing and won’t save you once the key is out.
Do environment variables keep API keys safe?
On a server, yes, mostly. In a frontend app, no: frontend frameworks copy certain environment variables straight into the code they ship.
An environment variable is a named value, like OPENAI_API_KEY, that your code reads at run time instead of having it typed into the file. It keeps keys out of your code and git history.
The catch is the build step. Browser frameworks pick out certain values by prefix and paste them into the JavaScript bundle:
| Framework or tool | Prefix that goes public | What its docs say |
|---|---|---|
| Vite | VITE_ | Exposed in client-side code after bundling; should not hold API keys |
| Next.js | NEXT_PUBLIC_ | Inlined into JavaScript sent to the browser at build time |
| Expo (React Native) | EXPO_PUBLIC_ | Visible in plain text in the compiled app; never for secrets |
| React Native config libraries | Any value they load | Fine for things like API addresses; not the same as server-side secrets |
| Bolt | PUBLIC_ or NEXT_PUBLIC_ | Compiled into the bundle and readable by anyone using the site |
Sources: Vite, Next.js, Expo, React Native, Bolt, all checked 6 December 2026.
Bolt’s glossary has the best line on this: a prefixed variable is not a secret, and it never was. I’d pin that above every desk.
Server-side environment variables are a different story. Stripe’s docs say to use your platform’s secrets vault first, and environment variables if no vault exists.
The OWASP secrets management cheat sheet is stricter. It says to avoid passing secrets through environment variables where you can, because they can leak through process listings, child processes and crash dumps.
For most small apps, a server-side variable on a reputable host is a fine start. Just never show it on an error page or in a public diagnostic mode, which Stripe warns about by name.
How do you hide an API key with a server-side proxy?
You move the call that needs the secret onto a server you control. The app asks your server, your server adds the key and calls the API, and the key never leaves the server.
That server can be tiny. The React Native docs suggest a serverless function (a small piece of code a cloud provider runs on demand, such as AWS Lambda) that forwards the request with the key attached. Supabase calls these Edge Functions; Bolt calls them server functions.
There’s a trap here, though. A proxy that forwards anything to anyone has just moved the problem. Google’s Maps security page gives two rules for proxies that I’d apply to every one:
- Don’t let clients relay arbitrary API calls through it. Your function should do one job, like “summarise this text”, and build the request itself.
- Always require authentication. Only signed-in users of your app should be able to call it.
Add a limit on how often one user can call it, and a spending cap at the provider if it offers one.
Here’s what the setup looks like in the AI builders people use most:
- Lovable: its docs say that when you paste a key into chat, it steers you to store it in Secrets and call the API from server-side code. Secrets live under More, then Secrets.
- Bolt: click the database icon at the top of the project, then Secrets. Bolt’s support page says a new secret is available to server functions straight away, and only the owner or a co-owner can see secrets in a shared project.
- Supabase: set secrets in the dashboard or CLI and read them in an Edge Function with Deno.env.get. Its docs warn that a committed .env file exposes every secret in it.
Our guide on how apps are built shows where this small server sits in a normal app.
Where should a mobile app store secrets on the phone?
In the operating system’s secure storage: the Keychain on iPhone, and on Android, data encrypted with a key held in the Android Keystore. That’s for things the user’s session needs, like login tokens, and never for your company’s API secrets.
People mix this up. A keychain protects a user’s own secrets on their own phone. It can’t protect a key you shipped to every phone, because that key still sits in the app file.
Apple’s Keychain Services docs describe it as a way to store small bits of user data in an encrypted database called a keychain. Passwords, keys, certificates and similar small secrets go there.
On Android, the Android Keystore holds cryptographic keys that can’t be exported, and your app uses one to encrypt the token it saves. When the key is bound to the phone’s secure hardware, Google says it can’t be pulled off the device even if the operating system is compromised.
What not to use:
- AsyncStorage in React Native. The React Native docs call it an unencrypted key-value store and list tokens and secrets as things not to keep there.
- Plain SharedPreferences on Android. React Native’s docs note it isn’t encrypted by default.
- localStorage in a web app. React Native’s docs call AsyncStorage its equivalent, so the same caution applies.
Older guides point Android developers to EncryptedSharedPreferences. Google’s Jetpack release notes show every API in that library was deprecated in favour of platform APIs and direct use of the Android Keystore, with version 1.1.0 released on 30 July 2025. If an AI tool suggests it in a new project, ask why.
Should you keep API keys in a .env file or a secrets manager?
A .env file is fine on your own laptop for development, as long as it’s listed in .gitignore. In production, use your host’s secrets store or a dedicated secrets manager.
A .env file is plain text. Anyone with access to the machine or the repository can read it.
Stripe describes what a proper secrets vault adds: your code refers to the key by name, every access is logged, rotation can be automated, and you can revoke access without redeploying. It names AWS Secrets Manager, Google Cloud Secret Manager, Azure Key Vault and HashiCorp Vault as examples. Our directories of hosting and cloud tools and backend and database tools list the options.
The bigger risk for most small teams is git. Once a key is committed, it’s in the history, even after you delete the file.
GitHub helps. Its secret scanning docs say scanning runs automatically and for free on public repositories, covers the entire git history on all branches, and notifies partner providers when it spots their keys so they can act.
Anthropic deactivates Claude keys that GitHub reports. Stripe says that when it detects an exposed key it asks you to rotate it, and in some cases deactivates it for you.
Treat them as safety nets. Stripe says it doesn’t guarantee to catch every exposed key, and private repositories can still leak through development machines.
How often should you rotate API keys, and what do you do after a leak?
Rotate immediately after any suspected exposure, and practise rotation on a schedule you choose so you know you can do it fast. None of the providers I checked sets one fixed interval.
Rotating means creating a replacement and switching the old key off.
The OWASP cheat sheet says rotation frequency should follow risk, such as how powerful the key is and how widely it’s exposed, rather than an arbitrary calendar.
Stripe says periodic rotation confirms you know where each key is used and can replace it on short notice. OpenAI recommends keys with an expiry date and a rotation process.
Stripe’s rotation tool is a good model for doing it without breaking anything. When you rotate in the dashboard, the old and new keys both work for up to 7 days, so you can switch your servers over and then let the old one expire.
After a leak, the order matters:
- Revoke or rotate the key first. Stripe says to rotate an exposed key immediately, even if you aren’t sure anyone saw it. Supabase puts it slightly differently: rotate a leaked key as soon as you fix the cause, so the new one doesn’t leak the same way. If the cause is a quick fix, do both in the same sitting.
- Check the usage logs. Look for requests you didn’t make. Stripe lets you open the request logs for each key, and OpenAI recommends watching your account usage.
- Find out how it leaked. Bundle, repository, chat message, screenshot, error page. Fix that, or the next key leaks the same way.
- Clean the code and history. OWASP’s cheat sheet says to delete the secret from the exposed systems, including code and logs.
- Tighten the replacement. Give the new key only the permissions it needs. Stripe’s restricted keys and Google’s API restrictions both exist for this.
If the leak exposed customers’ personal data, you may also have reporting duties. Our app legal requirements guide covers those.
Keep step 1 ahead of step 4. Deleting the line from your code does nothing to a key someone has already copied.
What do AI-built apps get wrong with API keys?
The same handful of things, over and over: secrets in frontend variables, the database’s secret key used in the browser, and database rules left off because the “public” key felt safe.
The best public evidence is the scan behind CVE-2025-48757. The researcher’s statement says 170 of 1,645 Lovable-built sites scanned had exposed data, across 303 endpoints, and the exposed data included API keys and Google Maps tokens. One sample endpoint was a database function called get_gemini_api_key.
The CVE record on NVD carries a 9.3 severity score and is tagged disputed, because Lovable’s position is that each customer is responsible for protecting their own app’s data.
These are the mistakes I’d check for first:
- A secret in a VITE_ or NEXT_PUBLIC_ variable. The AI wants the feature to work, and the quickest route is often a key the browser can read.
- The Supabase secret or service_role key in frontend code. Usually added to “fix” a permissions error, which it does by switching off every protection at once.
- Row-level security off. The publishable key is only safe with it on.
- A key pasted into the AI chat or committed to a public repository. Treat any key that has been anywhere public as exposed.
- A proxy that forwards anything. The key is hidden, but anyone can still spend it.
- One live key used everywhere. Supabase recommends a separate secret key for each backend component, so one leak means rotating one key.
If you built with AI and any of those sound familiar, our vibe coding safety guide walks through the other checks that catch the same kinds of app. If the list is long, our vibe coding cleanup cost guide explains what a fix usually involves and costs.
How do you check your own app for exposed keys?
Search what you actually ship, then check where each key lives and what it can do. The checklist below gives you a score and a report to hand to a developer.
The quickest test needs nothing but Chrome on a computer.
Open your live app, press F12, then Ctrl+Shift+F (Cmd+Option+F on a Mac) to search every loaded file. Search for sk_live, sk_test, rk_live, rk_test and sb_secret. Any match is a secret in public.
Older Supabase projects use legacy keys instead: long strings starting eyJ, where the public anon key and the secret service_role key look alike. If yours does, ask your developer or AI tool where the service_role key is used. The only right answer is server code.
API key safety checklist
API key safety checklist: 15 checks for where your app's keys live
Answer yes, no or not sure for each check. You get a score out of 100, what to fix first, and a report you can copy or print for your developer.
Found a secret in your bundle and not sure how to move it? That’s a good moment for a second pair of eyes.
For a bigger app, or one that takes payments or holds health or financial data, our guide on when to hire a developer for your AI-built app helps you decide how much help you need. And for the rest of the security picture, from logins to breach duties, go back to the full app security guide. Our app testing guide covers where security checks fit into testing before launch.
FAQ
Can someone steal my API key from my app?
Yes, if the key is inside the app’s code. Browser code is readable by every visitor, and anything in a phone app bundle can be read by someone who inspects it.
Is it safe to put an API key in a .env file?
On a server or your own laptop, yes, as long as the file is in .gitignore and never committed. In a frontend project, values with public prefixes such as VITE_ or NEXT_PUBLIC_ are copied into the code users download, so they are not secret.
Is the Supabase anon or publishable key safe to expose?
Yes, Supabase says it’s safe in web pages and apps, because row-level security controls what it can reach. Make sure row-level security is on for every table.
Can I hide an API key with obfuscation?
Not reliably. Google’s Android guidance says reverse engineering tools retrieve hard-coded secrets easily, so the dependable fix is to keep secret keys on a server and call them through your own function.
Where should I store user tokens in a mobile app?
In the Keychain on iOS, and on Android in storage encrypted with a key from the Android Keystore. Don’t use AsyncStorage, plain SharedPreferences or localStorage, which are not encrypted by default.
What should I do first if my API key leaked?
Revoke or rotate it at the provider straight away, before cleaning up code. Then check the usage logs for requests you didn’t make and fix whatever caused the leak.
How often should I rotate API keys?
Immediately after any suspected exposure, and otherwise on a schedule set by how powerful the key is. OWASP recommends basing the interval on risk.
Last Updated on December 6, 2026 by Ian Naylor