Documentation

Vanilla JavaScript Client SDK

The ModelRiver Vanilla JS SDK is the foundation of our client library. It is a lightweight, dependency-free class that manages WebSocket life-cycles, event emitting, and state persistence. Use it for projects without heavy frameworks or when building your own custom integrations.

Installation

npm

Bash
npm install @modelriver/client

CDN

For static sites or quick prototypes, include the SDK via our global CDN:

HTML
1<script src="https://cdn.modelriver.com/client/latest/modelriver.min.js"></script>

Implementation Example (Vanilla JS)

HTML
1<!DOCTYPE html>
2<html lang="en">
3<body>
4 <div id="ai-app">
5 <div id="progress"></div>
6 <div id="output"></div>
7
8 <input type="text" id="prompt-input" placeholder="Type your message...">
9 <button id="send-btn">Generate AI Response</button>
10 </div>
11 
12 <script type="module">
13 import { ModelRiverClient } from 'https://cdn.modelriver.com/client/latest/modelriver.esm.js';
14 
15 // 1. Initialize the client
16 const client = new ModelRiverClient({
17 baseUrl: 'wss://api.modelriver.com/socket',
18 debug: true
19 });
20 
21 const outputEl = document.getElementById('output');
22 const progressEl = document.getElementById('progress');
23 const inputEl = document.getElementById('prompt-input');
24 
25 // 2. Setup Event Listeners
26 client.on('response', (res) => {
27 outputEl.innerHTML = `<p>${res.content}</p>`;
28 if (res.data) {
29 outputEl.innerHTML += `<pre>${JSON.stringify(res.data, null, 2)}</pre>`;
30 }
31 });
32 
33 client.on('step', (step) => {
34 progressEl.innerText = `Current Step: ${step.name} (${step.status})`;
35 });
36 
37 client.on('error', (err) => {
38 outputEl.innerText = `Error: ${err}`;
39 outputEl.style.color = 'red';
40 });
41 
42 // 3. Handle Send Trigger
43 document.getElementById('send-btn').onclick = async () => {
44 outputEl.innerText = 'Initializing...';
45
46 // Request token from YOUR backend
47 const res = await fetch('/api/ai/start', {
48 method: 'POST',
49 headers: { 'Content-Type': 'application/json' },
50 body: JSON.stringify({ prompt: inputEl.value })
51 });
52
53 const { ws_token, channel_id } = await res.json();
54 
55 // Start the real-time AI stream
56 client.connect({ wsToken: ws_token, channelId: channel_id });
57 };
58 </script>
59</body>
60</html>

Key API Methods

client.connect(options)

Establishes the WebSocket connection. Requires wsToken (from your backend) and optionally channelId.

client.on(eventName, callback)

Subscribes to SDK events: connecting, connected, disconnected, channel_joined, channel_error, step, response, error, reconnecting (1.8.0+) and, for requests sent with "stream": true, stream_start, stream_delta, stream_done and stream_error (1.6.0+).

client.getState()

Returns the current state of the client, including status, response, steps, and whether it hasPendingRequest.

client.disconnect()

Safely closes the WebSocket connection and cleans up listeners.

client.reconnect()

Resumes the request stored in localStorage; call it on page load. It uses the stored single-use resume token, so a reload within about 5 minutes needs no backend call, and falls back to the getToken option when that token is stale or refused. Returns false when there's nothing to resume (SDK 1.8.0+). After network drops the client reconnects by itself. See Reconnecting.

client.detach()

Closes the connection and stops all timers but keeps the stored request, so the next page load or another client can resume it (SDK 1.8.0+).

Streaming Tokens and Live Sessions

For token-by-token text, send the async request with "stream": true and listen to stream_delta (SDK 1.6.0+). To follow a whole conversation live, including human agents' replies, use subscribeToSession (SDK 1.7.0+). See Streaming Tokens and Live Sessions.

HTML
1<script type="module">
2 import { ModelRiverClient, subscribeToSession } from 'https://cdn.modelriver.com/client/latest/modelriver.esm.js';
3 
4 // The answer as it streams in
5 const client = new ModelRiverClient({ persist: false });
6 client.on('stream_delta', (chunk, text) => {
7 document.getElementById('output').textContent = text;
8 });
9 
10 // The conversation, live
11 const subscription = subscribeToSession({
12 getSubscription: () => fetch('/api/chats/123/live', { method: 'POST' }).then((r) => r.json()),
13 onMessage: (message) => appendMessage(message),
14 });
15 window.addEventListener('pagehide', () => subscription.close());
16</script>

SEO Benefits of Vanilla JS AI

  1. Lightest Possible Bundle: By using zero-dependency Vanilla JS, your page stays incredibly lean, improving Core Web Vitals (LCP, FID) which are critical for SEO ranking.
  2. Instant Interaction: No framework initialization time means your AI interactive elements become usable as soon as the HTML is parsed.
  3. Universally Compatible: Works in every browser and can be injected into any CMS (WordPress, Shopify, Ghost) or legacy site to add modern AI features.

Next Steps