Deutsch
Fix libraryHighVite · Secrets

Secret key in a VITE_ variable: why .env doesn’t hide it, and how to move it

Every VITE_ variable ends up in the JavaScript your visitors download. Find secrets in VITE_ variables and code, rotate them and call the API from an edge function.

By Tim GeithnerPublished 4 min read

ShipRely's Security audit checks for this today.

Short answer

Vite copies every variable that starts with VITE_ into the JavaScript bundle at build time, so a secret in one is published to every visitor, even though it sits in a .env file. The same goes for a key written directly into frontend code. Rotate the key, move the code that needs it into an edge function that reads it from function secrets, and keep only public values such as the Supabase URL and publishable key in VITE_ variables.

Ask an AI about this page:ChatGPTClaude

On this page

A VITE_ environment variable is not a hiding place. Vite copies every variable with that prefix into the JavaScript it builds, so a secret key in one is downloaded by every visitor of your site, even though it lives in a .env file that never reaches git. It is rated high: whoever copies an AI or email key can run up your bill or send mail as you. If the key is a database admin key or a payment secret key, it is critical; the service_role key fix covers the Supabase case.

Why it matters

Vite’s documentation is direct: VITE_* variables “should not contain sensitive information such as API keys”, because their values are bundled into your source code at build time. Only variables with the prefix are exposed. Adding the prefix is the quickest way to make an “undefined” key work in the browser, and it works by publishing the key. We checked this with a production build: the value of a VITE_ variable appeared in the output JavaScript, and an unprefixed variable from the same .env file did not.

The typical shape is a feature that calls a paid API straight from React:

Vulnerablesrc/lib/ai.ts (sketch)
const res = await fetch("https://api.openai.com/v1/responses", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${import.meta.env.VITE_OPENAI_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify(payload),
});

OpenAI’s own guidance says never to deploy a key in browsers or mobile apps and to route requests through your own backend. The same holds for a key written directly into frontend code: in one of our test apps, a payment request was signed in the browser with a signing secret stored as a constant in src/lib/payments.ts. Our audit engine found both patterns in our test apps, the hard-coded signing secret as a high finding and the secret Supabase key in a VITE_ variable as a critical one.

ValueIn a VITE_ variable?
Supabase project URLYes
Supabase publishable or anon keyYes: built for browsers, your RLS policies protect the data
Stripe publishable key (pk_…)Yes: Stripe says it is safe in frontend code
Supabase secret or service_role keyNever
Stripe secret or restricted key (sk_…, rk_…)Never
Webhook signing secrets (whsec_…)Never
OpenAI or other AI provider keysNever
Keys for email, SMS or storage services, database passwordsNever

How to find it in your app

List every VITE_ variable that isn’t one of the known public ones, then search code and build output for well-known secret key shapes:

Find secrets in env files, source and build
grep -nE "^VITE_" .env* | grep -viE "PUBLISHABLE|ANON_KEY|_URL="
npm run build
grep -rnoE "sk-[A-Za-z0-9_-]{20,}|sk_live_[A-Za-z0-9]+|rk_live_[A-Za-z0-9]+|whsec_[A-Za-z0-9_]+|sb_secret_[A-Za-z0-9_-]+" src/ dist/

Read every name the first command prints: anything with SECRET, TOKEN, PRIVATE, SERVICE or an AI provider’s name in it is a problem. Also check vite.config.ts for an envPrefix setting, which changes which variables get exposed. On the live site, open DevTools, search all sources for the start of each key (sk-, whsec_, sb_secret_) and watch the network tab for requests that go from the browser straight to a paid API.

How to fix it

Rotate the key

Create a new key in the provider’s dashboard and revoke the old one. Everyone who loaded your site has had a copy, so moving it is not enough. If the key was ever committed, it also lives in your git history; see secrets in git history.

Store the new key as a function secret

In Supabase, add it under Edge Functions → Secrets, or with supabase secrets set OPENAI_API_KEY=… from the CLI. Use a name without the VITE_ prefix, and delete the old variable from every .env file and from your hosting settings.

Make the call from an edge function

The function reads the key from its environment, so it never reaches the browser:

Safesupabase/functions/ai-reply/index.ts (sketch)
Deno.serve(async (req) => {
  // Verify the caller's session here before doing paid work.
  const { prompt } = await req.json();
  const res = await fetch("https://api.openai.com/v1/responses", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${Deno.env.get("OPENAI_API_KEY")}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ model: Deno.env.get("OPENAI_MODEL"), input: String(prompt).slice(0, 4000) }),
  });
  return new Response(await res.text(), { status: res.status, headers: { "Content-Type": "application/json" } });
});

The frontend now calls supabase.functions.invoke("ai-reply", { body: { prompt } }). A function that spends money on every call needs an auth check and a spending limit; see edge function without auth check and no AI spend cap.

Move secret keys out of VITE_ variables

This Vite app exposes secret keys to the browser through VITE_ environment variables or constants in frontend code. List every VITE_ variable and every hard-coded key or signing secret in src/, and mark which ones are public by design (Supabase URL, Supabase publishable or anon key, Stripe publishable key). For every other one: move the code that uses it into a Supabase edge function that reads the secret with Deno.env.get under a name without the VITE_ prefix, verifies the caller’s session before doing any work, and is called from the frontend with supabase.functions.invoke. Remove the old variables from all .env files and the constants from the source.

Do not put any secret value into code, config or the prompt output. Remind me which keys I have to rotate in the provider dashboards.

Check that the fix works

Run the commands from “How to find it” again after a fresh build: the first must print only public names, the search in dist/ must find nothing. Open the live site in a private window, search the sources in DevTools for the old key’s first characters, and use the feature once: the network tab must show a request to your edge function, not to the paid API. Finally, look at the provider’s usage page for the old key: after rotation it must show no new requests. For the bigger picture of what may live in the frontend, read API keys in AI-built apps.

Frequently asked questions

My .env file is in .gitignore. Isn’t the key private then?

It stays out of git, but not out of the build. Vite replaces import.meta.env.VITE_… with the value while building, so the key ends up in the JavaScript file your site serves.

Which values are fine in a VITE_ variable?

Values that are meant to be public: the Supabase project URL, the Supabase publishable or anon key, the Stripe publishable key and similar IDs. Anything called secret, private, service or token, and any AI provider key, is not.

Can I obfuscate or encrypt the key in the frontend instead?

No. The browser needs the plain key to make the request, so anyone can read it at that moment in the network tab. The only fix is to make the request from a server.

Do I have to rotate the key if I remove it today?

Yes. Everyone who loaded your site before the change downloaded the key. Removing it from the next build does not take it back.

Sources

  1. 1.Env variables and modes — Vite
  2. 2.Environment variables in Edge Functions — Supabase Docs
  3. 3.Understanding API keys — Supabase Docs
  4. 4.API keys — Stripe Docs
  5. 5.Best practices for API key safety — OpenAI Help Center
  6. 6.CWE-798: Use of Hard-coded Credentials — MITRE

Find this in your own app

ShipRely reads your repository (read-only), proves each finding with file and line, and gives you a fix prompt to paste into your AI builder.

Run a demo audit
  • Read-only access to your repository
  • Every finding with file and line
  • Fix prompts for Lovable, Cursor, Claude Code and Bolt