Skip to content

How to hide an API key in an Expo app with a Cloudflare Worker

Keep your AI API key out of your Expo app bundle by calling the AI API through a small Cloudflare Worker. Setup, full code, and the limits of this approach.

Last updated:

TL;DR

Do not put an AI API key in your Expo app. Anything shipped in the bundle can be extracted. Store the key as a secret in a Cloudflare Worker, call the Worker from the app, and let the Worker call the AI API. This hides the key. It does not stop someone from calling your Worker, so lock the model, the token limit and the prompt inside the Worker and add rate limits.

Tested with

Not recorded.

Why the key cannot live in the app

Variables with the EXPO_PUBLIC_ prefix are inlined into the JavaScript bundle at build time. Anyone can download the app, unpack the bundle and read them. A key kept in app code or app config is public, even if it never appears on screen.

If the key is public, anyone can use it on your bill. The fix is to keep the key on a server and have the app talk to that server instead.

I ran into this while building Thoda, a weight-loss app made with Expo. The app sends meal text and food photos to an AI model, so the key had to stay off the phone.

Steps

Step 1: Create the Worker

npm create cloudflare@latest ai-proxy
cd ai-proxy

Choose the plain Worker template with TypeScript.

Step 2: Store the secrets

The Worker needs two secrets: the AI provider key, and a token the app sends so random traffic is rejected.

npx wrangler secret put ANTHROPIC_API_KEY
npx wrangler secret put APP_TOKEN

For local testing, create a .dev.vars file with the same names and values, and add .dev.vars to .gitignore. Never commit it.

ANTHROPIC_API_KEY=your-key-here
APP_TOKEN=any-long-random-string

Step 3: Set the model in the Worker config

Keep the model name in config, not in the app. Add it to your wrangler.jsonc:

{
  "vars": {
    "MODEL": "claude-haiku-5-5"
  }
}

Use whichever model your app needs. Check the provider's docs for current model names, since they change.

Step 4: Write the Worker

export interface Env {
  ANTHROPIC_API_KEY: string;
  APP_TOKEN: string;
  MODEL: string;
}

const MAX_TOKENS = 500;
const MAX_MESSAGES = 20;
const SYSTEM_PROMPT = "You are the assistant inside my app. Keep answers short.";

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    if (request.method !== "POST") {
      return new Response("Method not allowed", { status: 405 });
    }

    if (request.headers.get("x-app-token") !== env.APP_TOKEN) {
      return new Response("Unauthorized", { status: 401 });
    }

    let body: { messages?: unknown };
    try {
      body = (await request.json()) as { messages?: unknown };
    } catch {
      return new Response("Invalid JSON", { status: 400 });
    }

    if (!Array.isArray(body.messages) || body.messages.length === 0 || body.messages.length > MAX_MESSAGES) {
      return new Response("Bad request", { status: 400 });
    }

    const upstream = await fetch("https://api.anthropic.com/v1/messages", {
      method: "POST",
      headers: {
        "content-type": "application/json",
        "x-api-key": env.ANTHROPIC_API_KEY,
        "anthropic-version": "2023-06-01",
      },
      body: JSON.stringify({
        model: env.MODEL,
        max_tokens: MAX_TOKENS,
        system: SYSTEM_PROMPT,
        messages: body.messages,
      }),
    });

    return new Response(upstream.body, {
      status: upstream.status,
      headers: { "content-type": "application/json" },
    });
  },
};

The model, the token limit and the system prompt are fixed inside the Worker. The app can only send messages. It cannot ask for a bigger model, a longer answer or a different instruction.

Deploy it:

npx wrangler deploy

Wrangler prints your Worker URL, which looks like https://ai-proxy.your-name.workers.dev.

Step 5: Call the Worker from Expo

In your Expo project, add the Worker URL and app token to .env:

EXPO_PUBLIC_AI_URL=https://ai-proxy.your-name.workers.dev
EXPO_PUBLIC_APP_TOKEN=the-same-value-as-APP_TOKEN

Then call it:

export async function askAI(messages: { role: "user" | "assistant"; content: string }[]) {
  const res = await fetch(process.env.EXPO_PUBLIC_AI_URL!, {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "x-app-token": process.env.EXPO_PUBLIC_APP_TOKEN!,
    },
    body: JSON.stringify({ messages }),
  });

  if (!res.ok) {
    throw new Error(`AI request failed: ${res.status}`);
  }

  return res.json();
}

Restart Expo with a cleared cache after changing .env, because EXPO_PUBLIC_ values are read at build time:

npx expo start -c

The limit of this approach

EXPO_PUBLIC_APP_TOKEN is in the bundle too, so it is not a real secret. It only blocks casual abuse. A determined person can extract it and call your Worker.

What actually protects you:

  • A fixed model, max_tokens and system prompt in the Worker, as above.
  • A rate limit per IP or per device on the Worker. Cloudflare offers rate limiting features for this. Check their current docs for the setup that fits your plan.
  • A monthly spending cap on your AI provider account.
  • Per-user tokens, if your app has accounts. Thoda does not have accounts, so I rely on the first three.

Treat the app token as a speed bump, not as security.

What didn't work

My first plan for Thoda was a Supabase backend that would also hold the AI key. I dropped it because the free plan allows only two projects, and I wanted to keep those for other apps. A Supabase Edge Function could do the same job as this Worker, but a proxy does not need a database or a project slot, so a Worker was enough.

The EXPO_PUBLIC_ prefix is the other trap. It looks like it hides a value, but it only exposes it to the client code. Do not put the provider key behind that prefix, even in a private repo.

Common errors

The Worker returns 401 Unauthorized. The x-app-token header does not match the APP_TOKEN secret. Check the spelling, and remember that wrangler secret put sets the deployed value while .dev.vars sets the local one.

The AI API returns 401. The ANTHROPIC_API_KEY secret is missing or has a typo in its name. Run npx wrangler secret list to check which secrets exist.

The AI API returns 400. The messages array must start with a user message, and max_tokens is required. Make sure the app sends the right shape.

The app still uses an old URL or token. EXPO_PUBLIC_ values are inlined at build time. Restart with npx expo start -c.

It works in the simulator but not on a phone. If you point the app at a local URL, a physical phone cannot reach localhost. Use the deployed workers.dev URL.