Private Chat Frontend Development Guide: Secure Integration and Cost Control
This guide explains how to build a developer-owned chat frontend that calls standardized model provider APIs while keeping credentials, streaming data, context, and usage under control. It compares direct frontend connections with backend proxies, then covers secure credential handling, SSE parsing and incremental rendering, context trimming, historical data import/export, multi-capability abstraction, and cost governance for production use.
1. Scope and Boundaries
This article discusses a chat frontend built by developers themselves. It calls standardized interfaces provided by model service providers and places chat capabilities into the developer’s own pages. The example code targets Node.js 18 and later and modern browsers; both environments include built-in fetch, ReadableStream, and AbortController. Interface fields are subject to the documentation of the provider in use. Names such as your-model-name, choices, and delta in the examples are placeholders or common structures and must be checked item by item before integration.
Once the interface is standardized, application-layer work concentrates on four areas: where to store keys, how to parse streaming data, how to trim context, and how to control usage. The following sections address these four areas and also cover historical data migration, multi-capability abstraction, and a launch checklist.
2. Architecture Selection: Direct Frontend Connection or Backend Proxy
| Dimension | Direct frontend connection | Backend proxy |
|---|---|---|
| Deployment cost | Static hosting is sufficient | Requires an always-on service |
| Key security | Key is stored in the browser and readable by any script on the page | Key is used only on the server |
| Usage control | Mostly relies on user discipline | Supports authentication, rate limiting, budgets, and auditing |
| Cross-origin | Subject to the server’s CORS policy | Server forwards requests, not constrained by browser CORS |
| Use case | Prototype for personal use only | Multi-user access and production products |
The selection rule is straightforward. A direct frontend approach can be considered only when the app is used solely by the developer and the key is held only by that developer. Whenever multi-user access, shared quota, or sensitive data is involved, a backend proxy should be used.
A server’s CORS policy only determines which page origins can initiate cross-origin requests; it does not prevent key leakage. With a direct browser connection, the key enters the page, and any script that can read the page can obtain it. Therefore, direct connection must not be used for shared resources.
The recommended directory structure is as follows:
chat-app/├── server/│ ├── proxy.js # Backend proxy, holds the real key│ ├── usage.js # Usage statistics and budget checks│ └── .env # Environment variables, not committed to the repository├── web/│ ├── index.html│ ├── chat.js # Streaming requests and rendering│ ├── context.js # Context trimming│ └── importer.js # Historical data import validation└── .gitignore
3. Credentials and Security
3.1 Keep Keys on the Server Only
A production product should have a backend proxy hold the real key. The frontend receives only a session token issued after login. The token should have a validity period measured in minutes or hours and should be stored in an HttpOnly Cookie. HttpOnly Cookies cannot be read by JavaScript, which reduces the risk of credential theft through XSS attacks.
// server/proxy.js (Node.js 18+)import http from 'node:http';const UPSTREAM = process.env.UPSTREAM_BASE_URL;const API_KEY = process.env.UPSTREAM_API_KEY;const ALLOWED_MODELS = new Set(['your-model-name']);if (!UPSTREAM || !API_KEY) throw new Error('Missing UPSTREAM_BASE_URL or UPSTREAM_API_KEY');async function readJsonBody(req, limit = 1_000_000) {const chunks = [];let size = 0;for await (const chunk of req) {size += chunk.length;if (size > limit) throw Object.assign(new Error('Request body too large'), { status: 413 });chunks.push(chunk);}return JSON.parse(Buffer.concat(chunks).toString('utf8'));}const server = http.createServer(async (req, res) => {if (req.method !== 'POST' || req.url !== '/api/chat') {res.writeHead(404).end();return;}try {// Validate the session token first, then check rate limits and budget (see Section 8).const body = await readJsonBody(req);if (!ALLOWED_MODELS.has(body.model) || !Array.isArray(body.messages)) {res.writeHead(400).end();return;}const upstream = await fetch(`${UPSTREAM}/chat/completions`, {method: 'POST',headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${API_KEY}` },body: JSON.stringify({model: body.model,messages: body.messages,stream: true,max_tokens: Math.min(body.max_tokens ?? 1024, 4096),}),});res.writeHead(upstream.status, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' });if (upstream.body) {for await (const part of upstream.body) res.write(part);}res.end();} catch (err) {res.writeHead(err.status ?? 500).end();}});server.listen(8787);
Before forwarding, the proxy must do three things: limit the request body size, validate whether the model name is on the allowlist, and cap max_tokens. Otherwise, anyone could use the proxy to call expensive models or generate excessively long output.
3.2 Local Storage for Personal Use Only
If the app is used only by the developer, configuration can be stored in the browser, but the risk must be clearly disclosed and a one-click clear entry point must be provided. Clearing should delete the base URL, model name, and conversation data together, not just the key.
// web/storage.jsconst LOCAL_KEYS = ['api_base_url', 'api_key', 'model_name', 'conversations'];export function clearAllLocalData() {for (const key of LOCAL_KEYS) localStorage.removeItem(key);}
This approach is suitable only for personal prototypes. Shared computers, browser extensions, and any XSS vulnerability in the page can cause key leakage.
3.3 Prevent XSS in Rendering
Model output is untrusted content. Use textContent when rendering, and do not pass output directly to innerHTML. If Markdown formatting is needed, use a sanitized rendering library and disallow script execution and external resource loading.
4. Streaming Requests and Incremental Rendering
Most chat interfaces return data in Server-Sent Events (SSE) format. Each event consists of several lines. Data lines start with data:, and an empty line indicates the end of the event. Client-side parsing must handle the following cases:
- Network chunks may split a line, so a buffer must be maintained.
- Line endings may be
\nor\r\n. - A single event may contain multiple
data:lines, which must be joined with newlines before parsing. - At the end of the stream, the last line may lack a newline, and the final empty line may be missing; an explicit flush is required.
resp.bodymay be empty, in which case an explicit error must be raised.- If JSON parsing of a single event fails, terminate with an error instead of silently skipping it. Skipping would make the answer incomplete without the user noticing.
// web/chat.jsconst DONE = Symbol('done');export class HttpError extends Error {constructor(status) {super(`Request failed, HTTP ${status}`);this.status = status;}}function parseDelta(payload) {let json;try {json = JSON.parse(payload);} catch {throw new Error(`Streaming data is not valid JSON: ${payload.slice(0, 80)}`);}return json.choices?.[0]?.delta?.content ?? '';}export async function* streamChat(messages, { signal, endpoint = '/api/chat', model }) {const resp = await fetch(endpoint, {method: 'POST',headers: { 'Content-Type': 'application/json' },credentials: 'same-origin',body: JSON.stringify({ model, messages, stream: true }),signal,});if (!resp.ok) throw new HttpError(resp.status);if (!resp.body) throw new Error('Response body is empty; cannot read stream');const reader = resp.body.getReader();const decoder = new TextDecoder('utf-8');let buffer = '';let dataLines = [];const consumeLine = (raw) => {const line = raw.endsWith('\r') ? raw.slice(0, -1) : raw;if (line === '') {if (dataLines.length === 0) return null;const payload = dataLines.join('\n').trim();dataLines = [];return payload === '[DONE]' ? DONE : parseDelta(payload);}if (line.startsWith('data:')) {dataLines.push(line.slice(5).replace(/^ /, ''));}return null;};try {while (true) {const { done, value } = await reader.read();if (done) {buffer += decoder.decode();for (const raw of [...buffer.split('\n'), '']) {const out = consumeLine(raw);if (out === DONE) return;if (out) yield out;}return;}buffer += decoder.decode(value, { stream: true });let idx;while ((idx = buffer.indexOf('\n')) !== -1) {const raw = buffer.slice(0, idx);buffer = buffer.slice(idx + 1);const out = consumeLine(raw);if (out === DONE) return;if (out) yield out;}}} finally {// Release the connection on normal completion, error, or cancellation.await reader.cancel().catch(() => {});}}
The caller stops generation through an AbortController:
const controller = new AbortController();stopButton.addEventListener('click', () => controller.abort());let answer = '';try {for await (const text of streamChat(messages, {signal: controller.signal,model: 'your-model-name',})) {answer += text;outputEl.textContent = answer;}} catch (err) {if (err.name !== 'AbortError') showError(err);}
The retry rules are as follows. Retry only network errors, HTTP 429, and 5xx, at most twice, with exponential backoff, for example 500 milliseconds and 1 second, plus random jitter. If the stream fails after partial output, do not automatically replay from the beginning; otherwise duplicate text will appear. The correct approach is to keep the generated content and ask the user whether to continue or regenerate.
5. Session and Context Management
Chat interfaces are usually stateless, so every request must include historical messages. The model’s context window has an upper limit, and content beyond it is truncated or returns an error. Therefore, the client must actively control input length.
The input budget is calculated as follows:
Input budget = context window − max_tokens reserved for output − safety margin
Character count and token count are not the same thing. The conversion ratio between Chinese and English differs greatly, and the same text may have different token counts in different models. In production, use the counting endpoint provided by the service provider or a tokenizer matched to the model. Only fall back to character estimation when no counting method is available, and leave a larger safety margin.
Each message also has fixed overhead such as role markers. In the example below, PER_MESSAGE_OVERHEAD = 4 is only a placeholder and must be replaced according to the documentation of the model in use.
// web/context.jsconst PER_MESSAGE_OVERHEAD = 4; // Placeholder; refer to model documentationexport function trimHistory(messages, budget, countTokens) {const system = messages.filter((m) => m.role === 'system');const rest = messages.filter((m) => m.role !== 'system');const systemCost = system.reduce((sum, m) => sum + countTokens(m.content) + PER_MESSAGE_OVERHEAD, 0);let remaining = budget - systemCost;if (remaining <= 0) throw new Error('System prompt exceeds the input budget');const kept = [];let truncatedLatest = false;for (let i = rest.length - 1; i >= 0; i--) {const cost = countTokens(rest[i].content) + PER_MESSAGE_OVERHEAD;if (cost <= remaining) {remaining -= cost;kept.unshift(rest[i]);continue;}// If the latest message does not fit, truncate it instead of dropping it.if (kept.length === 0) {const allowance = remaining - PER_MESSAGE_OVERHEAD;if (allowance <= 0) throw new Error('Insufficient input budget; shorten the system prompt or reduce max_tokens');const content = truncateToTokens(rest[i].content, allowance, countTokens);kept.unshift({ ...rest[i], content });truncatedLatest = true;}break;}return { messages: [...system, ...kept], truncated: truncatedLatest };}function truncateToTokens(text, maxTokens, countTokens) {let lo = 0;let hi = text.length;while (lo < hi) {const mid = Math.ceil((lo + hi) / 2);if (countTokens(text.slice(0, mid)) <= maxTokens) lo = mid;else hi = mid - 1;}return text.slice(0, lo);}
This function keeps messages from newest to oldest, so the latest user input is always prioritized. When the latest message itself exceeds the limit, it is truncated, and the caller needs to show a notice to the user based on the returned truncated field.
Discarding old messages by round loses early agreements and background information. If the conversation needs to remain coherent over the long term, the model can generate a summary when a threshold is exceeded, and the summary can replace old messages. Summaries consume additional requests and cost and must be included in cost statistics.
6. Historical Data Import and Export
When users migrate historical conversations from other tools, common problems include inconsistent field structures, invalid role fields, empty or oversized content, and duplicate import of the same conversation. The import flow has four steps: parsing, validation, deduplication, and conflict handling.
In the first step, parse the file structure. Limit the file size, for example 20 MB, and reject files that exceed it. Then parse the JSON and check the top-level structure.
In the second step, validate each record. Roles are allowed only as system, user, and assistant; content must be a string, and a length limit must be set.
// web/importer.jsconst ALLOWED_ROLES = new Set(['system', 'user', 'assistant']);const MAX_MESSAGE_CHARS = 200_000;const MAX_FILE_BYTES = 20 * 1024 * 1024;export function parseImportFile(text) {if (new Blob([text]).size > MAX_FILE_BYTES) throw new Error('File exceeds the 20 MB limit');let data;try {data = JSON.parse(text);} catch {throw new Error('File is not valid JSON');}if (!Array.isArray(data?.conversations)) throw new Error('Missing conversations array');return data.conversations;}export function validateConversation(conv) {const errors = [];if (typeof conv?.id !== 'string' || conv.id === '') errors.push('Missing id');if (!Array.isArray(conv?.messages)) {errors.push('messages must be an array');return errors;}conv.messages.forEach((m, i) => {if (!ALLOWED_ROLES.has(m?.role)) errors.push(`Message ${i + 1} has an invalid role`);if (typeof m?.content !== 'string') errors.push(`Message ${i + 1} content must be text`);else if (m.content.length > MAX_MESSAGE_CHARS) errors.push(`Message ${i + 1} exceeds the length limit`);});return errors;}
In the third step, deduplicate. Compute a hash of the conversation content and use it as a fingerprint.
In the fourth step, handle conflicts. If the same id and the same content fingerprint exist, skip directly. If the same id exists but the content differs, save both copies by default, use a new id for the new conversation, and tell the user the reason. Overwriting old data requires explicit user confirmation.
The import process must be rollback-capable. Before importing, take a snapshot of existing data and store it separately. Batch writes must be in the same transaction and rolled back as a whole on failure. After import, keep an undo entry; undo restores the snapshot.
The field design of exported files should remain minimal:
- File header:
schemaVersion, export time, app version. - Each conversation:
id,title,model,createdAt,updatedAt. - Each message:
role,content,createdAt.
Export files must never contain API keys, service URLs, or session tokens. Before export, prompt the user that conversation content may contain personal information. A redaction option can be provided to replace phone numbers, email addresses, and ID numbers with regular expressions. However, regex redaction is best effort and cannot guarantee complete removal of sensitive information; the UI must state this.
If the export file contains conversation content, password encryption is recommended. Use the Web Crypto AES-GCM algorithm to encrypt, and do not save the password with the file. If the password is lost, the data cannot be recovered; clearly inform the user of this in the UI.
Deletion must also cover the full chain. When the user deletes a conversation, clear local storage, records in the IndexedDB, and in-memory caches at the same time, and inform the user that exported files will not be deleted by the application.
7. Unified Abstraction for Multiple Capabilities
Once interfaces are standardized, capabilities such as chat, speech recognition, and speech synthesis often come from different providers, with different authentication methods, parameter names, and error formats. The application layer should call these capabilities through a unified adapter interface and confine differences inside the adapters.
Each adapter declares its capability type and implements a unified invocation method. Callers depend only on the capability type, not on a specific provider.
Upstream errors need to be mapped to internal error codes. The mapping table below covers only common status codes; specific meanings are subject to provider documentation.
// server/providers/errors.jsexport class ProviderError extends Error {constructor(code, message, { status, retryable = false } = {}) {super(message);this.name = 'ProviderError';this.code = code;this.status = status;this.retryable = retryable;}}const CODE_BY_STATUS = {400: 'BAD_REQUEST',401: 'AUTH_FAILED',403: 'FORBIDDEN',429: 'RATE_LIMITED',};export function fromHttpStatus(status) {const code = CODE_BY_STATUS[status] ?? (status >= 500 ? 'UPSTREAM_ERROR' : 'UNKNOWN');const retryable = status === 429 || status >= 500;return new ProviderError(code, `Upstream returned HTTP ${status}`, { status, retryable });}const registry = new Map();export function registerProvider(kind, adapter) {registry.set(kind, adapter);}export function getProvider(kind) {const adapter = registry.get(kind);if (!adapter) throw new ProviderError('CAPABILITY_DISABLED', `Capability not enabled: ${kind}`);return adapter;}
Internal error codes allow frontend prompts and retry logic to handle only one set of rules. When adding a provider, only an adapter and mapping entries need to be added.
8. Cost Governance
Cost overruns usually come from three areas: growing input in long conversations, output limits set too high, and the lack of rate limiting and budget control. Governance must cover three stages: before the request, during the request, and after the request.
Before the request, estimate the cost and check the budget. Input tokens can be estimated using the counting method described earlier, and output is bounded by max_tokens. If the estimate exceeds the remaining quota, reject the request directly.
During the request, limit request frequency. A token bucket can be maintained per user to limit requests per minute and concurrency.
After the request, record actual usage and correct estimates. The usage field returned by the provider is the billing basis and should be used as the source of truth. Some services return usage only at the end of a streaming response, so values must be read according to the documentation.
The example below stores usage in memory and is suitable only for demonstration. Production should write to a database and ensure records do not contain conversation plaintext.
// server/usage.jsconst DAILY_BUDGET = 5; // Per-user daily budget, unit: currency units, example valueconst PRICE_PER_1K = { input: 0.002, output: 0.006 }; // Example unit prices; use official pricingconst ALERT_RATIO = 0.8;const spent = new Map(); // key is combination of user ID and datefunction dayKey(userId) {return `${userId}:${new Date().toISOString().slice(0, 10)}`;}export function estimateCost({ inputTokens, maxOutputTokens }) {return (inputTokens / 1000) * PRICE_PER_1K.input+ (maxOutputTokens / 1000) * PRICE_PER_1K.output;}export function checkBudget(userId, estimatedCost) {const current = spent.get(dayKey(userId)) ?? 0;return { ok: current + estimatedCost <= DAIL
