Phones and mobile apps2 minutes to read

How do I hide an OpenAI or other API key in my mobile app?

You can’t hide a key inside an app. Keep it on a small proxy API you host, and have the app call that, with limits so nobody can run up your bill.

Keep the key on a server, not in the app

You can’t hide a key inside a mobile app. Anything in the download, including build-time variables and obfuscated strings, can be pulled out by unpacking the app or watching its network traffic. Keep the OpenAI, Anthropic, Maps or payments key on a small API that you host. The app calls your API, and your API calls the provider with the key it keeps in its environment.

Which settings end up in the app

Expo inlines every EXPO_PUBLIC_ variable into the JavaScript bundle. Flutter compiles --dart-define values into the binary. Keys in Info.plist, strings.xml or a bundled .env file ship to every phone. Any of these is fine for your own API’s URL and wrong for a secret. See Expo’s environment variables guide.

A proxy route with limits

server.mjs (Express)
app.post('/v1/summarize', requireUser, rateLimit({ perMinute: 10 }), async (req, res) => {
  const text = String(req.body.text ?? '').slice(0, 4000);
  const reply = await fetch('https://api.openai.com/v1/responses', {
    method: 'POST',
    headers: {
      authorization: 'Bearer ' + process.env.OPENAI_API_KEY,
      'content-type': 'application/json',
    },
    body: JSON.stringify({ model: process.env.MODEL, input: 'Summarize: ' + text }),
  });
  res.status(reply.status).json(await reply.json());
});

Name the job (summarize) instead of forwarding any prompt the app sends. Require a signed-in user, cap the input size and limit requests per user. Then a copied request can’t be used to run your account up. On Bothosting, save OPENAI_API_KEY in the deployment’s Variables and restart. The free Spark plan’s 256 MB is plenty for a proxy like this.

If a key already shipped in an app

Rotate it at the provider now. Releasing a new build doesn’t help on its own, because old builds stay installed and the key is already in them. Put the replacement key on your API only, ship an app version that calls the API, and set a spending limit at the provider. The same rule applies to websites. Private API keys on a static website.