# How to Hide OpenAI API Key in Client-Side React Apps

> 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.

- Canonical page: https://realcomposer.com/recipes/hide-openai-api-key-react
- Client platform: React
- Upstream services: OpenAI
- Category: Security & Secret Vault
- JSON version: https://realcomposer.com/recipes/hide-openai-api-key-react.json
- Install in RealComposer (free plan, pre-fills this pipeline): https://realcomposer.com/dashboard/pipelines/new?recipe=hide-openai-api-key-react&via=agent

## Problem: 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

## Solution steps

1. **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.

2. **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.

3. **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" })
});
```

## Pipeline config

Import this config into a RealComposer pipeline. `{{secrets.NAME}}` values are read from the encrypted Secret Vault at request time, so the client never sees them.

```json
{
  "name": "React OpenAI Secure Proxy",
  "method": "POST",
  "cacheTtlSeconds": 0,
  "authMode": "client_token",
  "steps": [
    {
      "stepKey": "openai",
      "upstreamUrlTemplate": "https://api.openai.com/v1/chat/completions",
      "httpMethod": "POST",
      "headersTemplate": {
        "Authorization": "Bearer {{secrets.OPENAI_API_KEY}}",
        "Content-Type": "application/json"
      },
      "timeoutMs": 15000
    }
  ],
  "outputMapping": {
    "version": 1,
    "fields": [
      {
        "targetPath": "reply",
        "sourceStep": "openai",
        "sourcePath": "choices.0.message.content"
      },
      {
        "targetPath": "tokensUsed",
        "sourceStep": "openai",
        "sourcePath": "usage.total_tokens",
        "type": "number"
      }
    ]
  }
}
```

## Call the pipeline

```bash
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"}]}'
```

## Payload before and after

Raw upstream response:

```json
{
  "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"
}
```

Slimmed RealComposer response:

```json
{
  "reply": "RealComposer securely proxies your AI API requests at edge.",
  "tokensUsed": 30
}
```

## FAQ

### 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.
