← All posts

Josh Davies

If It Ships to the Browser, It's Public

A prefix in your .env file doesn't make a key safe. It makes it public on purpose. Anything in your bundle, your page props, or your inline scripts belongs to whoever opens DevTools. Here's how to keep secrets on the server, in TypeScript, Laravel, and WordPress.

  • security
  • typescript
  • react
  • laravel
  • wordpress
  • integrations

Somebody needs to call a third-party API from the frontend. The key is in .env. The frontend can't see it. So they rename it:

# before
MAPS_SECRET_KEY=abc123
 
# after
VITE_MAPS_SECRET_KEY=abc123

Now it works. Ticket closed.

And the key is sitting in a JavaScript file that every visitor downloads.

The prefix is the warning label

Build tools don't hide frontend env vars. They do the opposite.

Vite only exposes variables that start with VITE_ to your client code through import.meta.env. Next.js does the same thing with NEXT_PUBLIC_. Those prefixes exist so you can't leak a server secret by accident. You have to opt in.

Renaming the variable is opting in.

And it's not a lookup at runtime. The value gets replaced at build time. This:

const key = import.meta.env.VITE_MAPS_SECRET_KEY;

ends up in your built file as a plain string. Minified, sure. Minified isn't hidden. Open the network tab, search the JS for the first few characters of the key, and there it is.

It's not just env vars

The bundle is the obvious one. There are quieter ways to ship data to the browser.

Inertia props. Whatever you pass to Inertia::render() gets serialized into the page so your React or Vue component can read it. Anything shared in HandleInertiaRequests goes out on every single page.

// Sends every visible attribute on the user model
return Inertia::render('Settings', [
    'user' => $request->user(),
]);
 
// Sends what the page actually needs
return Inertia::render('Settings', [
    'user' => $request->user()->only('id', 'name', 'email'),
]);

$hidden on the model helps, but only for the columns somebody remembered to add. Picking fields on purpose is safer than hoping the model is configured right.

WordPress inline scripts. wp_localize_script() and wp_add_inline_script() print a <script> tag right into the HTML. Great for passing a nonce or an AJAX URL. Terrible for passing an API secret, because it lands in the page source for anyone to read.

wp_localize_script('my-plugin', 'MyPlugin', [
    'ajaxUrl' => admin_url('admin-ajax.php'),
    'nonce'   => wp_create_nonce('my_plugin'),
    // 'apiKey' => get_option('my_plugin_api_key'), // no
]);

Source maps. If you publish source maps to production, people can read your original source, comments included. Vite doesn't generate them for production builds unless you turn on build.sourcemap. If you did turn it on, know that you did.

The rule underneath all of these is the same. If the browser can read it, the user can read it. There's no setting that changes that.

Not every key is a secret

Some keys are built to be public, and that's fine.

Stripe gives you a publishable key (pk_) for the browser and a secret key (sk_) for the server. Pusher has a public app key and a separate app secret. Google Maps browser keys are meant to be in the page, and you lock them down with HTTP referrer and API restrictions in the Google Cloud console.

So the question isn't "is this a key?" It's "what can someone do with this key if they copy it?"

If the answer is "load a map on their own site, and only from my domain," that's a restricted public key. If the answer is "charge cards, read customer data, or run up my bill," it stays on the server. Full stop.

Put a server in the middle

When the frontend needs something only a secret key can get, the frontend asks your backend, and your backend asks the vendor.

In Laravel that's a small controller:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
 
class GeocodeController
{
    public function __invoke(Request $request)
    {
        $data = $request->validate([
            'address' => ['required', 'string', 'max:255'],
        ]);
 
        $response = Http::withToken(config('services.geo.secret'))
            ->timeout(5)
            ->get('https://geo.example.com/v1/search', [
                'q' => $data['address'],
            ]);
 
        abort_unless($response->successful(), 502);
 
        return $response->json('results.0');
    }
}
Route::get('/geocode', GeocodeController::class)
    ->middleware(['auth', 'throttle:30,1']);

The secret never leaves the server. The route requires a logged-in user and has a rate limit, because a proxy with no limits is just your secret key with extra steps. And you return only the piece the page needs, not the vendor's whole response.

The frontend calls your endpoint like any other:

type GeoResult = { lat: number; lng: number; label: string };
 
export async function geocode(address: string): Promise<GeoResult> {
  const params = new URLSearchParams({ address });
  const res = await fetch(`/geocode?${params}`, {
    headers: { Accept: 'application/json' },
  });
 
  if (!res.ok) {
    throw new Error(`Geocode failed: ${res.status}`);
  }
 
  return res.json();
}

No key anywhere in that file. Nothing to leak.

If you're on Next.js, the server-only package is worth a look. Import it at the top of a module that touches secrets, and the build fails if a client component ever imports that module. That's the kind of guardrail I like: the mistake breaks the build instead of shipping.

Check what you actually shipped

Don't trust the code review. Check the output.

After a build, search the files you're about to deploy for things that should never be there:

npm run build
grep -rEn "sk_live_|sk_test_|SECRET|PRIVATE KEY" public/build dist 2>/dev/null

public/build is where Laravel's Vite setup puts its output. dist is the Vite default. Adjust for your project.

You can make that a CI step so nobody has to remember it:

// scripts/check-bundle.ts
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
 
const patterns = [/sk_live_[A-Za-z0-9]+/, /sk_test_[A-Za-z0-9]+/, /-----BEGIN [A-Z ]*PRIVATE KEY-----/];
 
function walk(dir: string): string[] {
  return readdirSync(dir).flatMap((name) => {
    const path = join(dir, name);
    return statSync(path).isDirectory() ? walk(path) : [path];
  });
}
 
const hits = walk(process.argv[2] ?? 'dist').filter((file) =>
  patterns.some((p) => p.test(readFileSync(file, 'utf8')))
);
 
if (hits.length > 0) {
  console.error('Possible secrets in build output:\n' + hits.join('\n'));
  process.exit(1);
}

It won't catch everything. It will catch the most expensive mistakes, which is the point. Add patterns for the vendors you actually use.

Already shipped it? Rotate it

Deleting the variable and redeploying doesn't un-leak a key.

The old bundle may still be cached by a CDN or a browser. It may be in your git history. Somebody may have already copied it. Once a secret has been public, treat it as public forever.

So rotate it. Create a new key, move the server code over, revoke the old one. Then check the vendor's dashboard for usage you don't recognize.

It's annoying. It's a lot less annoying than the bill.

The habit

Before anything goes to the frontend, ask one question: am I okay with a stranger reading this?

If yes, ship it. If no, it lives on the server, and the browser asks the server for the result. A prefix in .env doesn't change the answer. It just means you answered "yes" without noticing.