{
  "slug": "hide-openai-api-key-react",
  "title": "How to Hide OpenAI API Key in Client-Side React Apps",
  "metaTitle": "Hide OpenAI API Key in React Apps - RealComposer",
  "metaDescription": "Hide your OpenAI API key in client-side React apps. Route requests through RealComposer edge endpoints to inject keys server-side with CORS protection.",
  "headline": "Secure Serverless OpenAI Edge Proxy for React, Vite, and SPAs",
  "category": "security",
  "categoryLabel": "Security & Secret Vault",
  "urgency": 10,
  "clientPlatform": "React",
  "upstreamServices": [
    "OpenAI"
  ],
  "searchIntentQuery": "hide openai api key in client side react app",
  "directAnswerSummary": "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.",
  "problem": {
    "title": "Why REACT_APP_ and VITE_ Environment Variables Are Not Secure",
    "explanation": "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.",
    "risks": [
      "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"
    ]
  },
  "solutionSteps": [
    {
      "stepNumber": 1,
      "title": "Add OPENAI_API_KEY to Secret Vault",
      "description": "Store your OpenAI key safely in RealComposer. It is encrypted at rest and never exposed to client browsers."
    },
    {
      "stepNumber": 2,
      "title": "Configure Edge Route with CORS Whitelisting",
      "description": "Create a POST /v1/:workspace/chat endpoint targeting https://api.openai.com/v1/chat/completions and set your allowed origin to https://yourdomain.com."
    },
    {
      "stepNumber": 3,
      "title": "Call from React Using Standard Fetch",
      "description": "In your React component, send user messages to RealComposer using your public client token.",
      "codeSnippet": "const res = await fetch(\"https://realcomposer.com/v1/acme/chat\", {\n  method: \"POST\",\n  headers: {\n    \"Authorization\": \"Bearer rc_live_...\",\n    \"Content-Type\": \"application/json\"\n  },\n  body: JSON.stringify({ prompt: \"Summarize text\" })\n});"
    }
  ],
  "pipelineConfig": {
    "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"
        }
      ]
    }
  },
  "sampleBloatedInput": {
    "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"
  },
  "sampleSlimmedOutput": {
    "reply": "RealComposer securely proxies your AI API requests at edge.",
    "tokensUsed": 30
  },
  "curlSnippet": "curl -X POST \"https://realcomposer.com/v1/acme/chat\" \\\n  -H \"Authorization: Bearer rc_live_your_client_token\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"messages\":[{\"role\":\"user\",\"content\":\"Hello\"}]}'",
  "faqs": [
    {
      "question": "Can I restrict the React OpenAI endpoint to only run from my domain?",
      "answer": "Yes. RealComposer Client Tokens allow you to restrict allowed CORS origins (e.g. https://myapp.com), blocking unauthorized domains from hitting your endpoint."
    },
    {
      "question": "Does this support response streaming?",
      "answer": "RealComposer passes standard and JSON chat completions natively with sub-10ms edge overhead."
    }
  ],
  "relatedRecipeSlugs": [
    "protect-openai-api-key-swift-ios",
    "call-private-api-from-webflow-securely",
    "combine-multiple-apis-into-single-json"
  ],
  "links": {
    "page": "https://realcomposer.com/recipes/hide-openai-api-key-react",
    "markdown": "https://realcomposer.com/recipes/hide-openai-api-key-react.md",
    "json": "https://realcomposer.com/recipes/hide-openai-api-key-react.json",
    "install": "https://realcomposer.com/dashboard/pipelines/new?recipe=hide-openai-api-key-react&via=agent"
  }
}