Self-Hosted Frontend for LLM Deployment: API Key Security and BFF Practices
This article explains how self-hosted frontend packages for large language models (LLMs) work, their practical boundaries, and deployment best practices. It covers browser-direct API calls, static deployment constraints, conversation data migration, the value and risks for developers and enterprises, and why a Backend-for-Frontend (BFF) layer should be the default for production. A minimal Node.js/Express BFF example is included, along with a checklist for enterprise deployment and common troubleshooting tips.
As large language models (LLMs) become widespread, developers and enterprises must balance convenience against data privacy. Two traditional approaches exist: using the model provider’s official web interface, or building a custom backend service to proxy API calls. Recently, some model platforms have begun offering self-hosted frontend application packages that users can deploy in local or private environments to create a chat interface, with the ability to import cloud-stored conversation history. This article explains how these packages work, their real-world limitations, and practical implementation steps.
1. Three Technical Characteristics of Self-Hosted Frontends
1.1 Browser-Direct Connections and Prerequisites
Traditional LLM web applications use a three-tier structure: frontend, backend, and model API. The backend forwards requests and stores API keys. A self-hosted frontend lets the browser send HTTPS requests directly to the model API, eliminating the need for a self-built middle layer. However, direct connections require two prerequisites. First, the model API must allow cross-origin requests from browsers (CORS). Second, the credentials used must be short-lived or issued by a server. A long-term API key stored in the browser can be read by any script on the same origin. Therefore, direct connections are suitable only for personal testing and low-sensitivity scenarios, not for holding production long-term keys.
1.2 Static Deployment and Runtime Conditions
Self-hosted frontends are typically distributed as compiled static files. Users do not need to install Node.js or run build commands; they only need to place the files on a static server, object storage, or an internal server. This reduces environment configuration overhead but still imposes runtime requirements: users need a working browser and network access. Double-clicking the local index.html file directly often causes the browser to treat the page as a file:// origin, breaking some API calls due to cross-origin restrictions. The recommended approach is to serve the page through a local HTTP server, for example by running python -m http.server.
1.3 Conversation Data Migration
Some platforms allow users to export historical conversations, typically as JSON. These files can be imported into the local frontend to resume conversations. This lowers migration costs, but several points require attention. First, confirm the structure version of the exported file; fields may differ between versions. Second, validate the JSON structure before importing and filter out anomalous fields. Third, set a file size limit to prevent large files from slowing down the browser. Fourth, if import fails, preserve the original file and support rolling back to the pre-import local data. Being able to export data does not clarify data ownership; specific rights are still governed by the service terms.
2. Value for Developers and Enterprises, and the Risks to Recognize
2.1 Shortened Prototyping Cycles
Developers do not need to build a chat interface, streaming message handling, or Markdown rendering from scratch. A ready-made frontend can serve as a foundation, allowing time to be spent on business logic validation. In internal knowledge base scenarios, teams can often put together a demonstrable prototype quickly. But a fast prototype does not mean it can go directly to production. Authentication, auditing, and key management still need to be added before release.
2.2 The Real Boundary of Privacy Protection
A self-hosted frontend places the interface and local data under user control, but request content is still sent to the model provider. Even if the frontend runs on an internal corporate network, as long as it calls a cloud model, prompts and attachments leave the network. Data masking can reduce exposure of sensitive information but cannot replace compliance review. Enterprises must also confirm the following: the process for handling a leaked key, the retention period for request logs and conversation records, and whether the provider uses inputs for model training—and whether the relevant terms meet industry regulatory requirements.
2.3 Secondary Development Space
Most such frontends are built on modern frameworks like React or Vue, with clear module structures, making them suitable for customization. Teams can integrate corporate SSO for unified login and embed model capabilities into OA, ticketing, or knowledge base systems. Each new integration point adds another authentication boundary that must be reviewed.
3. Implementation Practices
3.1 API Keys Should Not Be Stored in the Browser
A common anti-pattern is to encode an API key with btoa and store it in localStorage. This is not secure. Base64 is a reversible encoding format and provides no encryption; anyone with the string can use atob to recover the key. Content Security Policy (CSP) can reduce the risk of external script injection but does not prevent same-origin scripts from reading localStorage. Therefore, long-term keys should be kept only on the server side.
A more reasonable flow is: the browser stores only the user’s session credential, such as a cookie with HttpOnly and Secure flags. The BFF service verifies the user’s identity and then calls the model API using a server-side key. If direct browser-to-model calls are unavoidable, use short-lived tokens issued by the server, with short expiration times.
Below is a minimal BFF forwarding example, based on Node.js 18 or later and Express. The example assumes express-session is already configured; replace the model API URL and model name with actual values.
const express = require('express');const app = express();app.use(express.json({ limit: '1mb' }));// The key is read only from the server environment variable, never from frontend codeconst LLM_API_KEY = process.env.LLM_API_KEY;// Simple session check - only verifies that a user identifier exists in the sessionfunction requireSession(req, res, next) {if (!req.session || !req.session.userId) {return res.status(401).json({ error: 'unauthorized' });}next();}app.post('/api/chat', requireSession, async (req, res) => {const { messages } = req.body;if (!Array.isArray(messages) || messages.length === 0 || messages.length > 100) {return res.status(400).json({ error: 'invalid messages' });}const upstream = await fetch('https://api.llm-platform.com/v1/chat/completions', {method: 'POST',headers: {'Content-Type': 'application/json','Authorization': `Bearer ${LLM_API_KEY}`},body: JSON.stringify({ model: 'standard-model-name', messages })});if (!upstream.ok) {return res.status(502).json({ error: 'upstream request failed' });}res.json(await upstream.json());});app.listen(3000);
3.2 Enterprise Deployment Should Default to BFF
In enterprise environments, BFF should be the default architecture, not an optional extra. Use the following checklist during deployment:
- CORS: Only allow the official domain of the enterprise frontend. Do not combine the wildcard
*with credentialed requests. - Authentication: Integrate SSO, validate sessions or JWTs server-side, and control API access by role.
- Keys: Store keys in a key management service or environment variables, rotate them regularly, and log who uses them.
- Auditing: Record metadata such as user, time, model, and call volume. Whether to save prompt content depends on corporate policy.
- Conversation Storage: Encrypt history, set retention periods, and support per-user deletion.
- Rate Limiting: Limit call frequency per user and IP to prevent key abuse from causing cost spikes.
- Deployment: Serve frontend static files via CDN or object storage, run BFF in a container platform, and configure health checks.
3.3 Common Error Troubleshooting
- CORS failures: If the browser console shows cross-origin errors, the model API likely does not allow the current origin. Switching to a BFF proxy bypasses this issue because CORS rules are enforced by the browser, while server-to-server requests are not subject to them.
- Stolen keys: Check page code and storage for long-term keys, and check whether any third-party scripts are present. If a leak is found, revoke the key immediately in the provider’s admin console and re-issue a new one.
file://failures: Use a local HTTP server to serve the page instead of opening it directly.- Model API terms restrictions: Some models prohibit certain use cases or limit concurrency; read the relevant terms before going live.
- Import failures: Check the JSON structure version and fields, and confirm the file size is within limits.
Conclusion
Self-hosted frontends are suitable for personal learning, internal prototype validation, and low-sensitivity demos that do not require long-term keys. They are not suitable for production environments that hold long-term keys directly, process regulated sensitive data, or require centralized auditing and access control. When choosing an approach, first confirm whether the model API supports browser-direct connections, then decide if a BFF layer is needed. A self-hosted frontend lowers the barrier to building a chat interface, but it is only one part of the calling chain; the boundaries of key and permission management must still be enforced on the server side.
