Why is my free LLM API key missing in a Next.js Cloudflare Worker?
For an existing Next.js app using @opennextjs/cloudflare, read a Worker secret inside a server Route Handler with getCloudflareContext().env.CHINAGENAI_API_KEY. Configure the secret on the deployed Worker as a runtime binding. process.env can also expose Worker values with Node.js compatibility, so an empty value does not by itself prove the secret was never added. Keep the key on the server; never pass it to a client component or a NEXT_PUBLIC_ variable.
This guide is for maintaining an existing app on the OpenNext Cloudflare adapter. Cloudflare currently recommends vinext for new Next.js applications. Keep the recipes for these adapters separate: the route below uses @opennextjs/cloudflare and its documented request context.
Confirm which value and environment you are reading
There are three separate places a similarly named value can live:
| Value location | When it exists | What it is for |
|---|---|---|
Local Next.js .env file |
Local development | Lets next dev read a test value. It is not automatically uploaded with your Worker. |
| Build variable | Build or static generation | Available to the build process. A public NEXT_PUBLIC_ value can be embedded in browser assets. It is not a safe place for an API key. |
| Worker runtime Secret binding | When the deployed Worker handles a request | Holds the production credential for server code. OpenNext exposes bindings through getCloudflareContext().env. |
OpenNext documents .env files for local next dev and Cloudflare dashboard settings for production runtime variables. Workers Builds also has a separate build-time variables section. A production binding must be configured on the Worker and environment that actually receives the request; copying a local .env.local file into a deployment pipeline is not the same step.
Cloudflare's secret is a Worker binding. In OpenNext code, retrieve that binding from the route's Cloudflare context. This makes the source of the value visible and avoids confusing Next.js build-time substitution with the deployed Worker environment. Cloudflare also documents process.env access when Node.js compatibility is enabled; if your application uses that route, verify the compatibility date and flags for the Worker instead of assuming the secret value was deleted.
Add a production runtime Secret
In the Cloudflare dashboard, select the correct Worker and environment, open Settings → Variables and Secrets, add CHINAGENAI_API_KEY as type Secret, then deploy the setting. The name must match the code, including spelling and capitalization. Confirm you are looking at the Worker that handles your production hostname, not a preview or staging Worker.
The Wrangler command npx wrangler secret put CHINAGENAI_API_KEY also writes a Secret, but Cloudflare documents that it creates a new Worker version and deploys it immediately. Use it only when that deployment is intended. Do not add the key to plaintext vars, commit it in wrangler.toml, or build it into browser JavaScript.
If the Worker is deployed with Workers Builds, keep runtime secrets in the deployed Worker settings. Configure build variables separately only when the build genuinely needs a value. A chat API key should normally be needed by the request handler at runtime, not by static page generation.
Read it from a Route Handler
The following small example accepts one message, keeps the upstream URL fixed, and sends a non-streaming Chat Completions request. It demonstrates secret access; it is not a complete public proxy. Add your own authentication, request limits and rate limits before exposing an endpoint that can spend someone else's API quota.
import { getCloudflareContext } from "@opennextjs/cloudflare";
type MessageBody = { message?: unknown } | null;
export async function POST(request: Request) {
const { env } = getCloudflareContext();
const key = env.CHINAGENAI_API_KEY;
if (!key) {
return Response.json({ error: "LLM API secret is not configured" }, { status: 503 });
}
const input = await request.json().catch(() => null) as MessageBody;
if (typeof input?.message !== "string" || input.message.length === 0 || input.message.length > 4000) {
return Response.json({ error: "Expected a message of 1–4000 characters" }, { status: 400 });
}
const upstream = await fetch("https://chinagenai.com/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${key}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "free",
messages: [{ role: "user", content: input.message }],
stream: false,
}),
});
return new Response(upstream.body, {
status: upstream.status,
headers: { "Content-Type": upstream.headers.get("Content-Type") ?? "application/json" },
});
}
The browser calls your own route with a body such as {"message":"Write one sentence."}. It sends no provider authorization header. The route reads the Secret for that request and forwards to the fixed https://chinagenai.com/v1/chat/completions URL using the site model label free. The site route is an automatic upstream selection; it does not promise a named provider model. For the site's separate key and request rules, check the connection guide.
Do not turn this into an unrestricted relay. Require the user or application to authenticate before accepting a request, cap the body, rate-limit the caller, and keep the destination fixed. A hidden Worker secret does not prevent an unauthenticated public route from consuming its quota.
Use a separate local development value
For OpenNext's recommended next dev workflow, add initOpenNextCloudflareForDev() to the Next.js configuration as described in the OpenNext getting-started guide. OpenNext's environment-variable guide recommends a local Next.js .env file so next dev and the local Worker preview can read development values. Put only a synthetic key in the file and keep it out of Git.
For direct Wrangler Worker development, Cloudflare documents .dev.vars for local Secrets. Do not assume a file used by next dev is automatically loaded by every adapter or command. Choose one local workflow, follow its environment selection, and verify the binding in that workflow before debugging production.
Avoid reading a key during static generation. OpenNext notes that accessing bindings in SSG uses async mode and warns that local secrets and binding values can be used while pages are generated. Keep this API call in a request-time server route. Do not render the secret into HTML, a React Server Component payload, a page prop or a client bundle.
Diagnose the missing value in order
| What you observe | Check next |
|---|---|
getCloudflareContext().env.CHINAGENAI_API_KEY is empty in production |
Confirm the exact Worker, deployment environment, binding name and latest version. Check that the runtime Secret was deployed rather than only placed in a local file or build settings. |
process.env.CHINAGENAI_API_KEY is empty |
Check the Worker's Node.js compatibility settings. For OpenNext routes, compare with the adapter's documented getCloudflareContext().env access path. Do not infer that the dashboard secret is missing from this one read. |
It works in next dev but not after deployment |
The local .env value is not the production binding. Add a Secret to the Worker that serves the request, deploy that setting, then make a new request. |
| It works in one Worker but not another hostname | Check whether the hostname maps to a different preview, staging or production Worker. Secret bindings belong to the Worker/environment receiving the request. |
| A key appears in downloaded JavaScript or static HTML | Treat it as exposed: revoke or rotate that key, remove the public copy and rebuild. Changing the source protects future output, but does not erase a key from previously deployed assets or caches. |
Log a boolean such as Boolean(env.CHINAGENAI_API_KEY), the Worker environment and request ID while diagnosing. Do not log the secret value, authorization header, prompt, or full request object. If you need to prove the binding name, use a fake local value rather than printing a real key.
Test the boundary with a fake key
I used a synthetic LOCAL_ONLY_CHINAGENAI_KEY and an in-memory upstream stub. The test sends a fake browser request, injects a fake Worker context, and records the server-side fetch options. It checks four things: the client body contains only a message; the outbound URL is the fixed ChinaGenAI endpoint; the outbound bearer header contains the fake value; and neither the response nor the client request contains that value. A missing binding returns 503 before the stub is called; an invalid message returns 400 before fetch.
The fixture completed those checks with zero provider requests and no network access. This validates the sample handler's boundary under synthetic dependencies. It does not start Next.js, load @opennextjs/cloudflare, inspect a Cloudflare account, or prove that a deployed Worker has the right binding. Verify that part in a local Worker preview with a synthetic value, then check the correct production Worker setting without printing its value.
The API key must not be in a browser bundle, page source, source map or error response. If your local build uses a canary, search generated client assets for the exact fake string and verify it is absent. The expected bearer header should appear only in the server-side test capture. A successful unit test cannot replace a deployed runtime check, and a status message from the Worker cannot prove upstream quota or availability.
Common questions
Does a Cloudflare Worker secret always appear in process.env?
No single answer applies to every Worker configuration. Cloudflare documents process.env with Node.js compatibility, while OpenNext documents getCloudflareContext().env for its adapter bindings. Check the runtime and compatibility settings for the app you actually deployed.
Should I put the API key in NEXT_PUBLIC_CHINAGENAI_API_KEY?
No. A NEXT_PUBLIC_ value is intended for client-visible code. Keep the API key in a server-only Worker Secret and have the browser call your own authenticated route.
Should I use .dev.vars for next dev?
Follow the adapter's documented development setup. OpenNext recommends Next.js .env files for its next dev workflow; Cloudflare documents .dev.vars for Wrangler local Worker development. A value in one file is not proof it loaded in the other command.
Can I read the secret while generating a static page?
Avoid it. A chat API key is a runtime credential. OpenNext warns that local secrets and binding values can be used during SSG. Put the call in a request-time server route and return only the result needed by the caller.
Sources checked 2026-11-10
- OpenNext bindings —
getCloudflareContext().env, local binding access, and SSG caution. - OpenNext environment variables — local
.env,NEXTJS_ENV, production runtime values and--keep-vars. - Cloudflare OpenNext adapter — existing-app scope, compatibility setup and vinext recommendation for new apps.
- Cloudflare Worker Secrets — Secret bindings, Node.js compatibility, local files and deployment behavior.
- Original developer question — one report of a configured Worker secret not appearing through
process.envin a Next.js route.