How to Hide OpenAI API Key in Client-Side React Apps
Secure Serverless OpenAI Edge Proxy for React, Vite, and SPAs
To use OpenAI in a client-side React app without leaking your secret key, never include OPENAI_API_KEY or REACT_APP_OPENAI_API_KEY in frontend .env files. Instead, route your fetch calls through a RealComposer edge endpoint that injects your secret key server-side on Cloudflare Workers and enforces CORS origin whitelisting.
Why REACT_APP_ and VITE_ Environment Variables Are Not Secure
In React, any environment variable prefixed with REACT_APP_ or VITE_ is inlined directly into your bundled JavaScript code during build time. Web crawlers, scrapers, and botnets automatically scan GitHub repos and deployed sites for sk-proj-... tokens, draining API credits within minutes.
- Immediate quota exhaustion and surprise multi-thousand-dollar OpenAI bills
- Automated API key revocation by OpenAI safety bots
- Abuse by third parties using your credentials for unauthorized inference
How RealComposer Solves This at the Edge
Add OPENAI_API_KEY to Secret Vault
Store your OpenAI key safely in RealComposer. It is encrypted at rest and never exposed to client browsers.
Configure Edge Route with CORS Whitelisting
Create a POST /v1/:workspace/chat endpoint targeting https://api.openai.com/v1/chat/completions and set your allowed origin to https://yourdomain.com.
Call from React Using Standard Fetch
In your React component, send user messages to RealComposer using your public client token.
const res = await fetch("https://realcomposer.com/v1/acme/chat", {
method: "POST",
headers: {
"Authorization": "Bearer rc_live_...",
"Content-Type": "application/json"
},
body: JSON.stringify({ prompt: "Summarize text" })
});
{
"id": "chatcmpl-98a7bc6",
"object": "chat.completion",
"created": 1712000000,
"model": "gpt-4o",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "RealComposer securely proxies your AI API requests at edge."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 18,
"completion_tokens": 12,
"total_tokens": 30
},
"system_fingerprint": "fp_a98214"
}
{
"reply": "RealComposer securely proxies your AI API requests at edge.",
"tokensUsed": 30
}
curl -X POST "https://realcomposer.com/v1/acme/chat" \
-H "Authorization: Bearer rc_live_your_client_token" \
-H "Content-Type: application/json" \
-d '{"messages":[{"role":"user","content":"Hello"}]}'Developer Questions & Troubleshooting
Can I restrict the React OpenAI endpoint to only run from my domain?
Yes. RealComposer Client Tokens allow you to restrict allowed CORS origins (e.g. https://myapp.com), blocking unauthorized domains from hitting your endpoint.
Does this support response streaming?
RealComposer passes standard and JSON chat completions natively with sub-10ms edge overhead.
Deploy this React + OpenAI Recipe
Clone this pre-configured pipeline into your RealComposer workspace in one click. We pre-populate upstream URLs, headers, and mapping rules.