Skip to content
<Notes of dev/>

Is your API key in your JavaScript bundle?

20 min read

The squirrel hands a string-tied bundle of prints across the counter, and a ferret in a red cap reaches for the brass key tucked under the string.

How API keys and CMS tokens reach your JavaScript bundle past green scanners, and how to check what your live site really serves.

Part 2 of 4 in the "Are you sure your website is safe?" series

TL;DR

Next.js copies every NEXT_PUBLIC_ value that client code reads into the JavaScript each visitor downloads, so any API key there is public. Secret scanners stay green through it because the key never enters git. Keep them, add a regular check of the deployed site, and rotate any leaked key without downtime.

A green pipeline with a token in the bundle

Picture a small Next.js site on a headless CMS. Every push runs a shift-left security stack: SonarCloud, CodeQL, GitHub secret scanning with push protection, ESLint security rules and pnpm audit. SonarCloud reports security rating A, 0 vulnerabilities and 97.9% test coverage. CodeQL runs 87 rules and returns nothing.

Headless CMS — a content management system that stores content and serves it through an API (application programming interface), leaving the pages to a separate framework such as Next.js.

Shift-left — running security checks early, on the code in the repository, before anything ships.

But a CMS preview token sat in a JavaScript file that every visitor downloaded, and anyone who found it could read unpublished drafts. In the same weeks, an encoded address rendered internal CMS fragments as public pages, and the publish webhook compared its secret with a plain !==. No tool flagged any of it.

Part 1 split "safe" into four layers. This post covers the first: what your code ships to browsers. It answers the title question first, then covers the other gaps the example site also had: the webhook secret, an internal route and dependency installs.

If you followed Set up Dependabot, CodeQL, and the install delay, or the security phase in AI-generated code ships hidden vulnerabilities, you already run most of these scanners. They read the repository, and the leak lived in the build.

How NEXT_PUBLIC_ ships a secret to every browser

Next.js keeps environment variables on the server by default. For any variable that client code reads, the NEXT_PUBLIC_ prefix flips that rule: Next.js will "inline" the value "at build time, into the js bundle that is delivered to the client" (Next.js environment variables docs). The prefix means public, for a CMS token or any other API key.

Think of a NEXT_PUBLIC_ value as text on a printed flyer. The build is the print run, and every visitor walks away with a copy. Changing the variable later does not change flyers already handed out; the value stays frozen until the next build. The analogy stops at one point. You cannot recall a flyer, but you can revoke a token.

On the example site, the client-side CMS SDK (software development kit) started like this:

typescript
'use client';
import { apiPlugin, storyblokInit } from '@storyblok/react';

storyblokInit({
  accessToken: process.env.NEXT_PUBLIC_STORYBLOK_TOKEN,
  use: [apiPlugin],
});

The browser never called the CMS API itself, so the token had no job on the client. The fix moves it into a module that only server code can import:

typescript
import 'server-only';
import { apiPlugin, storyblokInit } from '@storyblok/react/rsc';

export const getStoryblokApi = storyblokInit({
  accessToken: process.env.STORYBLOK_TOKEN,
  use: [apiPlugin],
});

If a client component ever imports this file, server-only fails the build (Next.js data security guide). The full server-side setup is in How to set up Storyblok with Next.js.

Which CMS token leaked decides the damage

A leaked token can only do what its type allows, and CMS vendors split types by job:

  • Public token — reads published content; Storyblok says "Use this token in production frontends" (Storyblok access tokens). In a bundle, it exposes what your site already shows.
  • Preview token — reads "draft and published content" and belongs in "the Visual Editor or staging environments" (same page). In a bundle, it exposes everything you have not published yet.
  • Management or personal token — creates, changes and deletes content. Contentful says a management token has "the same rights as the owner of the account" (Contentful authentication). In a bundle, it lets a stranger rewrite your site.

The example site had shipped a preview token. Calling the delivery API with it and version=draft returned draft content. Every post was already published, so no unreleased post had leaked yet, but every future draft would have.

Intruder scanned about 5 million applications and found over 42,000 exposed tokens of 334 types in JavaScript bundles (Intruder research).

Three panels of the ferret: lifting a print off a display rack, unlocking a drawer of draft sketches with a brass key, and swapping the print on a press for a fish engraving.
The token type decides how much damage a leak can do.

Check the deployed bundle and source maps for secrets

Run the bundle scan against the deployed site, since the repository never held the token. On the example site, a first scan searched for a token-shaped pattern and wrongly reported "no token". The scan that works compares the downloaded files with the real value.

Chunk — one of the JavaScript files a Next.js build splits your code into, served from /_next/static/.

The squirrel lifts the top print from an unwrapped parcel and stares at a brass key underneath while a rabbit points at it.
Check the built bundle, where the key actually ships.

In practice: the bundle scan

The script downloads the pages you list, every chunk their HTML (HyperText Markup Language) references and any source map published next to a chunk. Then it searches all of it for a value you paste, which never reaches the screen or your shell history.

Source map — a file that maps minified JavaScript back to the original source code, with file paths and comments.

bash
#!/usr/bin/env bash
set -euo pipefail

SITE="https://www.example.com"
PAGES=("/" "/a-post-slug")
read -rsp "Value to search for (hidden): " NEEDLE; echo

WORK=$(mktemp -d)
for page in "${PAGES[@]}"; do
  curl -fsS "$SITE$page" >> "$WORK/pages.html"
done
grep -oE '/_next/static/[^"\\]+\.js' "$WORK/pages.html" | sort -u > "$WORK/chunks.txt"

while read -r chunk; do
  curl -fsS "$SITE$chunk" -o "$WORK/$(echo "$chunk" | tr '/' '_')"
  map="$WORK/map$(echo "$chunk" | tr '/' '_')"
  if [ "$(curl -s -o "$map" -w '%{http_code}' "$SITE$chunk.map")" = "200" ]; then
    echo "public source map: $chunk.map"
  else
    rm -f "$map"
  fi
done < "$WORK/chunks.txt"

if grep -rqF -- "$NEEDLE" "$WORK"; then
  echo "FOUND in the deployed site"
else
  echo "Not found in $(wc -l < "$WORK/chunks.txt" | tr -d ' ') chunks"
fi
rm -rf "$WORK"

It covers only chunks referenced in those pages' HTML, so list one page of each type (home, post, archive). Run it once per server-side secret you hold: the CMS preview and management tokens and the webhook secret.

Next.js disables production browser source maps by default (Next.js productionBrowserSourceMaps), but testers still append .map to a bundle address to check, as the OWASP (Open Worldwide Application Security Project) testing guide shows.

When the bundle scan finds a token, ask the CMS what it can read. For Storyblok:

bash
read -rsp "Token (hidden): " TOKEN; echo
curl -s -o /dev/null -w '%{http_code}\n' \
  "https://api.storyblok.com/v2/cdn/stories?version=draft&token=$TOKEN"

A 200 means the token can read drafts. Treat it as a preview token until your CMS settings say otherwise.

Rotate a leaked token without downtime

Revoking the token at once feels safe. Do not do it first. The running build still has the old value baked in, like the flyers already printed, so production cannot fetch content until a build with the new token deploys. Rotate in this order:

  1. Remove the token from client code. Read a server-only variable with no NEXT_PUBLIC_ prefix, as in the module above.
  2. Create a new token and add it to the host and to CI (continuous integration). Leave the old one active; the current build still depends on it.
  3. Deploy.
  4. Run the bundle scan for both the old and the new value. Neither should appear.
  5. Revoke the old token, then call the API with it. On the example site it returned 401, so the copies already in browsers became useless.

Finish step 5. Leaked secrets often stay live for years; GitGuardian's 2026 report found 64% of valid secrets from 2022 still exploitable (State of Secrets Sprawl 2026).

Keep the new value out of browser fields, the clipboard and AI (artificial intelligence) tool calls. Pass it through a file only you can read:

bash
TMP=$(mktemp)
read -rsp "New server token (hidden): " T; printf '%s' "$T" > "$TMP"; unset T
gh secret set STORYBLOK_TOKEN < "$TMP"
vercel env add STORYBLOK_TOKEN production < "$TMP"
rm -f "$TMP"
A badger locksmith kneels to fit a new brass lock in the shop door while the squirrel serves a rabbit at the counter; the old lock lies in a toolbox on the floor.
Deploy the new token first, revoke the old one last.

Protect the webhook secret and its host

The webhook secret is the other server-side secret the bundle scan should search for, and its route can fail in two more ways. When an editor publishes, the CMS calls a route on your site, and that route refreshes the cache. If your CMS signs its webhooks, verify the signature. Without one, the usual design puts a secret in the query string, /api/revalidate?secret=.... Query strings end up in logs, so rotate that value whenever it appears somewhere unexpected.

The example route compared the secret with !==, under a comment that called the check timing-safe.

Timing attack — guessing a secret by measuring how long each wrong guess takes to be rejected, since a plain comparison stops at the first character that differs.

The fix hashes both sides with SHA-256 (Secure Hash Algorithm, 256-bit) and compares the digests with timingSafeEqual. Hashing gives both buffers the same length, which timingSafeEqual requires, so the comparison time reveals nothing.

typescript
import { createHash, timingSafeEqual } from 'node:crypto';
import { revalidateTag } from 'next/cache';
import { NextResponse, type NextRequest } from 'next/server';

const digest = (value: string) => createHash('sha256').update(value).digest();

function isValidSecret(received: string | null): boolean {
  const expected = process.env.REVALIDATE_SECRET;
  if (!expected || received === null) return false;
  return timingSafeEqual(digest(received), digest(expected));
}

export async function POST(request: NextRequest) {
  if (!isValidSecret(request.nextUrl.searchParams.get('secret'))) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }
  revalidateTag('storyblok', { expire: 0 });
  return NextResponse.json({ revalidated: true });
}

How webhook delivery fails in prod

The example webhook pointed at the bare domain (example.com), which answered with a 307 redirect to www. The CMS did not follow it. Every delivery failed for weeks, and publishes never refreshed production. Nothing alerted, because the site stayed up. Point the webhook at the exact host your pages use, and read the CMS delivery log after the next publish.

Internal CMS routes reachable by an encoded path

Headless sites often keep shared fragments in the CMS, such as a global/ folder with the header and footer. They should never render at an address of their own.

The example site blocked them in middleware with pathname.startsWith('/global'). A request for /%67lobal/header (%67 is the encoded letter g) passed, because the middleware saw the raw path, and the page rendered the header with status 200. Even the blocked path answered 200 instead of 404.

The fix checks the route param, which reaches the page decoded, and returns a real 404:

typescript
import { notFound } from 'next/navigation';

const isPageSlug = (slug: string) => slug !== 'global' && !slug.startsWith('global/');

export default async function Page({ params }: { params: Promise<{ slug: string[] }> }) {
  const { slug } = await params;
  const fullSlug = slug.join('/');
  if (!isPageSlug(fullSlug)) notFound();
  // fetch and render the story
}

Run the same check in generateMetadata. Check access where the route uses the decoded value, since a string match in middleware sees a different string.

Why the shift-left stack stayed green

SAST — Static Application Security Testing, tools that read source code for known dangerous patterns without running it.

Each scanner reads one place, and the leaks sat elsewhere:

  • Secret scanning and push protection read git. GitHub scans "your entire Git history across all branches" (GitHub secret scanning), and push protection stops secrets "before they reach your repository" (GitHub push protection). The token lived in the host's settings and entered JavaScript during the build.
  • SAST and CodeQL see a documented pattern. storyblokInit({ accessToken: process.env.NEXT_PUBLIC_... }) is normal code. Whether the value is a public or a preview token is a fact stored in the CMS.
  • Sonar judges new code and skips some files. The default "Sonar way" gate checks coverage and duplication on new code only (SonarQube Cloud quality gates), and secrets detection skips Markdown and HTML files, .env.dev* and .env.test* files, test folders and low-entropy strings (SonarQube secrets detection). A value the build adds never reaches either check.
  • Lint rules match code shapes. eslint-plugin-security has 15 rules for Node patterns and none for hardcoded secrets (eslint-plugin-security).
  • pnpm audit reads advisories. It compares your lockfile with known vulnerable versions, so routes, webhooks and CMS settings are outside its view.

What the scanners still do well

A fair objection: if the scanners missed every issue here, why keep them? For this site the objection holds. OWASP says source code analysis tools "can automatically identify only a relatively small percentage of application security flaws" and are "frequently unable to find configuration issues" (OWASP Source Code Analysis Tools).

But OWASP also says static analysis "scales well" and "can be run repeatedly", so it catches well-known flaws on every push at almost no cost. On the example site, 581 commits of git history held no secrets and git ignored .env* files, so the repository layer was clean.

Keep the scanners, and add a check of the deployed site. OWASP's DevSecOps guideline calls this "shift-left (and increasingly shift-everywhere)" (OWASP DevSecOps Guideline).

Add a check of the deployed site

DAST — Dynamic Application Security Testing, scanners that probe the deployed site from the outside, the way an attacker would.

On the example site, an AI agent with a security brief reviewed the code and the running site, then confirmed each finding from outside: it ran the bundle scan, called the CMS API with the token it found, and requested encoded paths. Part 4 covers how that review ran and what the agent was not allowed to do.

In practice: a release routine for the deployed site

Run the bundle scan after every production deploy, and ask the CMS what each token it finds can read. Point a DAST scanner at the deployed site at least once per release. For the encoded-path check, both requests should print 404:

bash
SITE="https://www.example.com"
for path in /global/header /%67lobal/header; do
  echo "$(curl -s -o /dev/null -w '%{http_code}' "$SITE$path") $path"
done

Repeat the whole routine monthly, and after any change to routing, tokens or webhooks.

Close the supply-chain gaps before install

pnpm audit only knows advisories that already exist, and a freshly compromised package has none yet.

Example: chalk and debug in 2025

In September 2025 a phished maintainer led to 18 npm packages with "more than 2 billion downloads per week" shipping a browser-based interceptor that rewrote crypto-wallet payment destinations (Aikido on debug and chalk). That code ran in the browsers of people visiting sites that bundled it.

In practice: five supply-chain defences

Without an install delay, a release like that can reach your bundle and your visitors before the registry removes it.

  1. Delay installs. pnpm's minimumReleaseAge refuses versions younger than the setting, by default 1440 minutes since v11, because "malicious releases are discovered and removed from the registry within an hour" in most cases (pnpm settings).
  2. Add a Dependabot cooldown. On the example site, CI's frozen-lockfile install skipped pnpm's age check, so the lockfile needs a second gate. Dependabot applies "a default cooldown period of 3 days to version updates", though not to security updates (Dependabot options reference).
  3. Gate auto-merge on the PR (pull request) author. github.actor is whoever triggered the run, so it can be Dependabot when Dependabot only updated someone else's pull request.
  4. Pin Actions to a full commit SHA. GitHub recommends the full commit ID, since tampering with a pinned commit would need "a SHA-1 collision" (GitHub Actions secure use).
  5. Never check out untrusted code in pull_request_target. That trigger runs with your repository's secrets, and the same page warns that checking out an untrusted pull request there can "expose the repository".

The author gate is one line in the auto-merge job:

yaml
if: github.event.pull_request.user.login == 'dependabot[bot]'

Pinning costs upkeep; a small site can defer it if it accepts trusting whoever controls the Action's version tag. The Dependabot and install delay guide has the full configuration.

Frontend secrets: do, don't, and what happens if you skip it

Keep CMS tokens server-side

  • Do — read tokens from server-only variables.
  • Don't — pass a preview or management token to a client SDK.
  • If you skip it — anyone can read your drafts from the bundle, and a management token lets them change your content.

Scan the deployed bundle and source maps

  • Do — run the bundle scan for every server-side secret after each deploy.
  • Don't — treat green scanners as proof.
  • If you skip it — a leak the build created stays live while every scanner stays green.

Rotate in order

  • Do — follow the five rotation steps and revoke last.
  • Don't — revoke the old token first.
  • If you skip it — production cannot fetch content until the new token deploys.

Protect the webhook secret and its address

  • Do — compare hashed secrets with timingSafeEqual and point the webhook at the final host.
  • Don't — use !==, or an address that redirects.
  • If you skip it — publishes can fail silently for weeks, as they did on the example site.

Check decoded paths for internal routes

  • Do — reject internal slugs after decoding, with a real 404.
  • Don't — rely on a raw startsWith check in middleware.
  • If you skip it — internal CMS fragments render as public pages.

Delay installs and gate auto-merge on the PR author

  • Do — set an install delay and a Dependabot cooldown, and check who opened the pull request.
  • Don't — auto-merge on github.actor, or check out untrusted code in pull_request_target.
  • If you skip it — a freshly compromised package can ship to your visitors, and an untrusted checkout can "expose the repository".

SHA pinning is optional hardening on top.


Until something checks the deployed site, a green dashboard only tells you the repository is clean, and the bundle your visitors download can say otherwise.

Next up: Would you know if your website was hacked?, on Google Search Console and Bing Webmaster Tools as an early alarm for hacked or unwanted pages.


The "Are you sure your website is safe?" series: Part 1