What is it?
JavaScript runs in two important places for AI products: the browser (UI) and Node.js (server). The same language can implement a chat form and the route that proxies to a model. The critical rule is separation of trust: anything shipped to the browser is public.
Why it matters
Many demos call a model API directly from the browser with a key in the bundle. That key will leak. Production AI apps use JavaScript on the client for UX and JavaScript (or another language) on the server for model calls, authentication and logging.
How to do it
- Build the chat UI with HTML/JS or React.
- From the browser,
fetchyour backend route (same origin or controlled CORS), not the model vendor. - On the server (Node.js for AI Applications), read
process.env.MODEL_API_KEY, call the vendor, return text or a stream. - Authenticate the end user before spending tokens.
- Treat model output as untrusted HTML — escape before inserting into the DOM (What is Prompt Injection? risks if you render Markdown carelessly).
Example
Browser (no vendor key):
const res = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message: userText }),
});
if (!res.ok) throw new Error("chat failed");
const data = await res.json();
appendAssistant(data.text);
Server route holds the key and calls the model (see Calling AI Services from JavaScript and TypeScript and Node.js for AI Applications).
When to use it
Choose JavaScript when your product UI is web-based or your team already runs Node services. Prefer Python for heavy data science batch jobs if that is the team skill set (Python for AI: When and How to Use It) — both can coexist.
Practical notes
Structure the repo so 'web/' never imports server secret modules. Share only TypeScript types or JSON schemas across the boundary. Add a simple health route that does not call the model so load balancers stay cheap. For local development, run the UI and API on known ports and proxy '/api' to Node to avoid CORS distractions. Log request ids on the server and echo them to the client error banner so users can report failures. Remember that browser extensions and XSS can read anything in page memory — another reason the vendor key must never appear in JavaScript shipped to the browser. When you add file uploads for RAG, scan and size-limit on the server before any model sees the bytes.
Common mistakes
- Embedding API keys in Vite/Webpack bundles.
- Calling the model from the browser "temporarily" and shipping it.
- Rendering raw model HTML without sanitisation.
- Skipping auth on the proxy route so anyone can burn your quota.