Pure Static Chat Frontend: API Keys, CORS, Streaming, and Field Troubleshooting

    This article examines the practical boundaries of a purely static chat frontend. It covers when this architecture is appropriate, how to manage API key exposure and incident response, how CORS preflight and SSE streaming work with browser fetch, and how to design a field adapter layer with regression and troubleshooting checklists.

    1. Conclusions and Applicable Scenarios

    A purely static chat frontend fits two scenarios: personal use on a local machine, or team use inside an intranet where users are trusted and data sensitivity is low. It is not suitable for public multi-tenant services, centralized key hosting, or businesses with strict compliance requirements.

    Before adopting it, answer two questions: who holds the key, and who bears the consequences if it leaks? The table below helps with that decision.

    Dimension Suitable Not suitable Key ownership and breach responsibility
    Deployment Opened locally, or statically hosted on an intranet Publicly open to unknown users Deployer responsible
    Key management Users hold their own low-privilege, revocable keys Organization centrally hosts a master key Each user bears responsibility
    Compliance No explicit audit or data retention requirements Requires audit logs, data residency, or classified protection Written allocation of responsibility required
    Maintenance cost Simple features, few dependencies Requires multi-tenant billing, quotas, and risk controls Dedicated maintainer required

    Requests from a purely static app originate in the user’s browser. Anyone who opens developer tools can see the key in the request headers in the Network panel. Therefore, this approach can only reduce the exposure surface, limit the damage from a leak, and shorten rotation time. It cannot guarantee that the key will never be seen.

    2. Risk Checklist and Inspection Steps

    The table below lists six common problem categories. Each item includes an inspection method and a remediation step so the list can be checked before launch.

    Risk Typical symptom Inspection step Remediation
    Key leakage Key appears in source code, build artifacts, screenshots, or commit history Search the dist directory and run a secret scanning tool Revoke immediately, generate a new key, and review usage logs
    Public abuse Strangers access the site and consume quota Confirm whether the deployment URL is publicly reachable Take it offline or add access control; for public scenarios, switch to a server-side proxy
    Script injection Model output is rendered as HTML, and scripts read stored keys Check whether Markdown rendering is sanitized and whether CSP is configured Use a sanitization library and restrict connect-src in CSP to provider domains only
    CORS failure Browser blocks the request and the console shows a cross-origin error Inspect OPTIONS preflight response headers in the Network panel Verify whether the provider supports browser calls; add a proxy if necessary
    Streaming interruption Response stops midway Record the last event received and its timestamp Keep the output already shown and ask the user to regenerate
    Missing fields UI shows undefined or blank content Print the full response JSON Map fields in the adapter layer and set defaults

    3. Key Storage and Breach Containment

    API keys cannot be truly hidden in the frontend. The steps below reduce the chance of leakage and limit the damage after a leak.

    1. Do not put keys in source code or build configuration. Tools such as Vite inline environment variables with the VITE_ prefix into frontend bundles; those values are effectively public.
    2. Have users enter the key manually on the page. By default, keep it only in memory so it is lost on refresh. If persistence is required, use sessionStorage with an expiration time instead of storing it long-term in localStorage.
    3. Use only low-privilege, revocable, dedicated keys. Do not give the organization’s master key to the frontend.
    4. Set monthly usage caps and per-minute rate limits in the provider console.
    5. Run secret scanning before committing code, and scan historical commits as well. For example, with gitleaks:
    1. gitleaks detect --source . --verbose
    1. After building, inspect the output to make sure no key prefix remains. Replace the prefix in the command below with the actual format of the provider’s key:
    1. grep -rn "sk-" dist/ || echo "No matches found"
    1. After a leak, follow this order: revoke the old key, generate a new key and update users’ local configuration, review usage logs to identify the time and source of anomalous calls, and finally document the incident and conduct a retrospective.

    4. CORS Requests and SSE Stream Parsing

    CORS Requests and Preflight

    Before sending a cross-origin request, the browser sends an OPTIONS preflight request if the request has custom headers such as Authorization or a Content-Type of application/json. The provider’s response must include headers such as Access-Control-Allow-Origin; only after the preflight passes is the actual request sent.

    Keep three points in mind during implementation:

    • The API key is placed in the request header and does not rely on cookies, so there is no need to set credentials: 'include'. If you do set it, the provider’s Access-Control-Allow-Origin must not be the wildcard *.
    • Whether a provider allows direct browser calls depends on its official documentation. Some providers do not allow it, in which case the browser will always block the request.
    • Preflight failure looks different from actual request failure. On preflight failure, the request body is not sent, and the console only shows a cross-origin error.

    Common errors and how to handle them:

    • No 'Access-Control-Allow-Origin' header is present: The provider does not allow calls from the current origin. Change the endpoint or use a proxy.
    • Response to preflight request doesn't pass access control check: OPTIONS returned a non-2xx status or is missing allowed request headers.
    • Credentials and wildcard conflict: Remove credentials: 'include', or have the provider return a specific origin.

    There are three alternatives. For local development, use Vite’s server.proxy to forward requests so they become same-origin and no longer trigger CORS. For intranet use, use an Nginx reverse proxy. For public-facing scenarios, use a server-side proxy or cloud function to hold the key; at that point the solution is no longer a purely static frontend.

    SSE Stream Parsing

    EventSource only supports GET requests and cannot set custom request headers. Most chat APIs require a POST body and an Authorization header, so fetch is typically used to read the response stream.

    The function below demonstrates basic reading and line-by-line parsing:

    1. export async function streamChat(url, body, apiKey, onEvent, signal) {
    2. const res = await fetch(url, {
    3. method: 'POST',
    4. headers: {
    5. 'Content-Type': 'application/json',
    6. Authorization: `Bearer ${apiKey}`,
    7. },
    8. body: JSON.stringify({ ...body, stream: true }),
    9. signal,
    10. });
    11. if (!res.ok) {
    12. throw new Error(`HTTP ${res.status}: ${await res.text()}`);
    13. }
    14. const reader = res.body.getReader();
    15. const decoder = new TextDecoder('utf-8');
    16. let buffer = '';
    17. // Return false when the end marker is received
    18. const handleLine = (raw) => {
    19. const line = raw.replace(/\r$/, '');
    20. if (!line.startsWith('data:')) return true;
    21. const data = line.slice(5).trim();
    22. if (data === '[DONE]') return false;
    23. try {
    24. onEvent(JSON.parse(data));
    25. } catch (err) {
    26. console.warn('Skipping unparsable event', err);
    27. }
    28. return true;
    29. };
    30. while (true) {
    31. const { done, value } = await reader.read();
    32. if (done) break;
    33. buffer += decoder.decode(value, { stream: true });
    34. const lines = buffer.split('\n');
    35. buffer = lines.pop();
    36. for (const line of lines) {
    37. if (!handleLine(line)) return;
    38. }
    39. }
    40. buffer += decoder.decode();
    41. if (buffer) handleLine(buffer);
    42. }

    Pay attention to the following during parsing:

    • Use TextDecoder with stream: true to avoid cutting multibyte characters and producing garbled text.
    • A single data chunk may contain only half a line. The code keeps the last incomplete line and waits for the next chunk to concatenate.
    • Each event starts with data:, and events are separated by blank lines. Comment lines starting with a colon should be ignored.
    • Some providers use [DONE] to indicate the end. End markers differ across providers, so handle them according to the documentation.
    • A single bad event should not interrupt the whole answer, so JSON.parse should be wrapped in try.

    After a disconnect, fetch does not resume automatically. If the failure occurs before the first token appears, you can retry 429 and 5xx responses with exponential backoff, honor the Retry-After header, and retry at most two or three times. Do not automatically resend an answer that has already started streaming; doing so can double-bill and produce two partial responses.

    The stop button should call abort() through an AbortController and stop UI rendering at the same time.

    5. Field Adaptation and Troubleshooting

    Field Differences Across Providers

    Request and response structures differ across providers. The table below lists the main differences among three common API styles. Refer to each provider’s official documentation for exact field names and versions.

    Semantics OpenAI-style Anthropic-style Gemini-style
    System prompt A messages item with role set to system Top-level system field systemInstruction field
    Maximum output length max_tokens or max_completion_tokens max_tokens (required) generationConfig.maxOutputTokens
    Authentication Authorization: Bearer x-api-key and anthropic-version x-goog-api-key or URL parameter
    Streaming text location choices[0].delta.content delta.text in a content_block_delta event candidates[0].content.parts[0].text
    Finish reason finish_reason: stop or length stop_reason: end_turn or max_tokens finishReason: STOP or MAX_TOKENS
    Error structure error.message, error.type type is error, containing error.type and error.message error.code, error.message, error.status

    The Anthropic API requires an additional dedicated request header for direct browser access; requests without it are rejected. Confirm the header name in the documentation.

    Adapter Layer Design

    Do not read each provider’s raw fields directly in UI components. Add an adapter layer that normalizes responses from different providers into an internal structure such as { text, finishReason, error }. The UI then handles only one structure, and adding a provider requires changing only the adapter layer.

    The adapter layer should also handle the following:

    • Provide defaults for missing fields. For example, return an empty string instead of undefined when text is missing.
    • Normalize each provider’s error structure into { code, message } so the UI can show a readable message.
    • Map finish reasons to a unified enum so the UI can identify whether an answer was truncated.

    Regression Checklist

    After each change to the adapter layer or upgrade of a provider SDK, check the following:

    1. Run the same set of prompts on each provider and confirm that outputs display correctly.
    2. During a long response, disconnect the network and confirm that already-rendered content remains and the UI shows a prompt.
    3. After clicking the stop button, confirm that the request is canceled and the UI stops appending text.
    4. Trigger 401, 429, and 500 manually and confirm that the UI messages match the causes.
    5. Scan the dist directory and git history again to confirm that keys did not enter build artifacts or commits.

    Troubleshooting Table

    Symptom Possible cause Inspection method Handling
    CORS error in console Provider does not allow the current origin, or preflight failed Check OPTIONS response headers Verify documentation; change endpoint or use a proxy
    401 returned Wrong key or incorrect Authorization format Check request header content and prefix format Re-enter the key and confirm prefix requirements
    429 returned Rate or quota exceeded Check Retry-After header and console usage Back off and retry, reduce concurrency, or raise quota
    Request succeeds but no output SSE not parsed line by line, or Content-Type mismatch Print raw data chunks Fix line-buffering logic
    Answer stops midway Network interruption or server timeout Record the last received event Preserve existing output and prompt regeneration
    UI shows undefined Response structure differs from expected Print the full response JSON Map fields in the adapter layer and set defaults
    Garbled multibyte text Multibyte characters split Check whether decoder uses stream: true Use a streaming decoder
    Key disappears after refresh Key is kept only in memory This is expected behavior Use sessionStorage if persistence is needed and inform users of the risk

    The boundaries of a purely static approach should be decided before launch. If public access is required, put the key in a server-side proxy rather than handing it to the browser.