Your site's functions can now remember things: a key-value store for every site, on Pro and Team.Build an app with sign-in

How to call an API from a static site without shipping the key

Anything in a static site's files is public, environment variables included. The key has to live one hop away, in something that adds it to the call — and on most hosts that is one config block or a fifteen-line function.

Your page needs to call a paid API — OpenAI, a weather service, your own backend — and the API wants a secret key. A static site is files, and every file is downloaded by every visitor. So the key cannot be in the files: not in the JavaScript, not in a .env that the build inlines, not "obfuscated".

The fix is always the same shape. Put a tiny proxy between the page and the API. The page calls a path on its own site, such as /api/chat. The proxy holds the key, adds it to the request, forwards the call, and hands back the answer. The key never leaves the server side.

Your site stays static. Only that one call goes through something else. What differs between hosts is where the proxy lives and whether you write code for it.

The 30-second version

Host Where the key lives What you write
Netlify environment variable, read by a function a function file of about fifteen lines
Vercel environment variable, read by a route one routes entry in vercel.json, no code
Cloudflare Pages secret on context.env a Pages Function of about ten lines
GitHub Pages nowhere on the host — it runs no code a proxy somewhere else, such as a Worker
Drop2Run the site's API settings or function variables, encrypted one line of _redirects, or a short function

Why hiding it in the files does not work

A static host hands every visitor the same bytes, so anything a page knows, a visitor can read. Minifying does not change that. Neither does splitting the key into pieces or encoding it.

Build tools are explicit about it. Vite says that variables prefixed with VITE_ will be exposed in client-side source code, and that they should not contain API keys. Next.js says a NEXT_PUBLIC_ value is inlined into any JavaScript sent to the browser. The prefix is a warning label, not a lock.

The API providers say the same from their side. OpenAI's reference tells you not to expose the key in any client-side code such as browsers, and its official Node library refuses to run in a browser unless you set an option literally named dangerouslyAllowBrowser. A leaked key is spent by whoever finds it, on your bill.

Calling through your own path has a second benefit: the page and the proxy share an origin, so there is no CORS to configure. A browser lets a script read a cross-origin answer only when that server sends Access-Control-Allow-Origin, and many APIs never will.

The proxy, host by host

Every example below forwards a chat request to OpenAI. Swap the URL and the header for whatever API you use.

Netlify

A redirect rule with status 200 can proxy to another origin, but it cannot carry the key: environment variables cannot be used directly as values in netlify.toml. So on Netlify the proxy is a function. Set OPENAI_API_KEY in the site's environment variables, then add a function file:

JS
// netlify/functions/chat.mjs
export default async (req) => {
  if (req.method !== "POST") return new Response("Method not allowed", { status: 405 });

  const { messages } = await req.json();
  return fetch("https://api.openai.com/v1/chat/completions", {
    method: "POST",
    headers: {
      "content-type": "application/json",
      authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
    },
    body: JSON.stringify({ model: "gpt-4o-mini", messages }),
  });
};

export const config = { path: "/api/chat" };

The function reads the key with process.env, and the page calls fetch("/api/chat", …). Note that it picks the model itself rather than forwarding whatever the page sent — more on why below.

Vercel

Vercel can do this without a function. A route can set a request header from an environment variable at request time, and a route to an external URL works as a reverse proxy:

JSON
{
  "routes": [
    {
      "src": "/api/chat",
      "dest": "https://api.openai.com/v1/chat/completions",
      "transforms": [
        {
          "type": "request.headers",
          "op": "set",
          "target": { "key": "authorization" },
          "args": "Bearer $OPENAI_API_KEY",
          "env": ["OPENAI_API_KEY"]
        }
      ]
    }
  ]
}

The variable has to be listed in env, or the $ reference stays a literal string. This version forwards the request body untouched, so the page chooses the model; if that matters, write a Vercel Function instead, shaped like the Netlify one above.

Cloudflare Pages

A file under functions/ becomes a route, and a secret set in the project's settings is available on context.env and cannot be read back once saved:

JS
// functions/api/chat.js
export async function onRequestPost({ request, env }) {
  const { messages } = await request.json();
  return fetch("https://api.openai.com/v1/chat/completions", {
    method: "POST",
    headers: {
      "content-type": "application/json",
      authorization: `Bearer ${env.OPENAI_API_KEY}`,
    },
    body: JSON.stringify({ model: "gpt-4o-mini", messages }),
  });
}

onRequestPost answers only POST; the API reference lists the other method handlers.

GitHub Pages

GitHub Pages is a static site hosting service and runs no code of yours, so the proxy has to live on another host. A Cloudflare Worker is the usual pick: the same function as above, with the key stored by wrangler secret put. Because the Worker is on a different origin from your pages, it has to send the CORS headers itself — name your site's origin in Access-Control-Allow-Origin rather than *.

Drop2Run

Here the proxy is part of the host. Declare the API once in the site's API connections tab — its origin, and the header with the key — then point a line of _redirects at it:

TEXT
/api/chat/*    https://api.openai.com/v1/chat/:splat    200

The page calls /api/chat/completions on its own address, and the call goes out with the header attached. The value is encrypted when saved and shown afterwards only as its last four characters. Only GET passes until you open other methods for that API, a write has to carry the site's own address as its Origin, and an answer that is HTML is refused. The rules and limits are in the redirects documentation. Like the Vercel rule, it forwards the body as sent.

To fix the model or reshape the call, write a function instead, on the Pro and Team plans: a file such as _functions/api/chat.js exporting onRequestPost({ request, env }), much like the Cloudflare one above, with the key read from env. The key is set in the site's Functions tab, never published, and the functions documentation has the rest.

The proxy is public too

This is the part the tutorials that rank for this question skip, and the first thing their readers ask in the comments. Moving the key off the page stops people reading it. It does not stop them using it: your /api/chat answers anybody who calls it, from your page or from a script.

Checking the Origin header does not close that gap. It stops another web page from calling your proxy through a visitor's browser, but OWASP is plain that Origin is not access control — outside a browser it can be anything. What actually limits the damage:

  • A key with the least access it needs. A project key limited to one model or one endpoint, not your account's master key.
  • A spending cap at the provider, where the provider offers one. It is the only limit that holds no matter how the key is used.
  • Fix what the caller cannot choose. The Netlify and Cloudflare examples set the model in the proxy, and so can a function of your own on any host that runs one. A proxy that forwards the body as-is lets anybody pick the most expensive model you have access to.
  • A rate limit that answers 429 when requests come too fast.
  • A login in front, for an internal tool. A proxy behind the site's password or sign-in is only as public as the site.

When not to do this

When the provider gives you a key made for browsers. Some APIs split their keys exactly so you do not need a proxy. Stripe's publishable key is safe to include in front-end code; the secret one is not. Supabase's publishable key is readable by anyone and reaches only what Row Level Security allows. Use those as designed, and do not proxy the secret key to fill a gap that row-level rules should fill. If the key is for a database, the six places a static site can keep data compares this with the other options.

When each visitor needs their own identity. A proxy holding one key makes every caller the same caller. If the API has to know who is asking — per-user data, per-user billing — you need real sign-in and a backend that maps users to permissions, and that is no longer a static site with one dynamic call. The page on what "static" actually means draws that line in more detail.

When the visitor brings the key. A tool where each user pastes their own key can call the API straight from the browser. That key is theirs to expose.

Questions

Is a .env file safe on a static site?

Only if nothing in it reaches the output. A build that inlines a variable into the bundle publishes it, and a .env copied into the output folder is a file anyone can download. Keep the key in the host's environment settings, where only the proxy reads it.

Can I hide the key with obfuscation or encryption in the page?

No. The page has to turn it back into the real key to use it, and the code that does that is in the same files. Anything the browser can do, a visitor can repeat.

Do I need CORS if I use a proxy?

Not when the proxy answers on the same origin as the page, which is the case for every host above except GitHub Pages. A proxy on another origin has to send the CORS headers itself.

Can somebody else use my proxy?

Yes, anybody who finds the path. That is why the key behind it should be limited, capped and rate-limited — the proxy stops the key from being copied, not from being spent.

What about long answers from a language model?

Ask the model to stream. A streamed answer starts arriving almost at once, so the proxy never sits idle long enough to hit a host's time limit on waiting, and the reader sees words instead of a spinner.

This site is the product it is written about.

Drag a folder in and read the link back. No account and no card to publish.