Browser Client
You can connect from a browser with the native WebSocket API. No library is needed. This page shows a complete client that subscribes, keeps the connection alive and reconnects.
A key in a web page is visible to everyone who opens it. Use the browser only for short tests and internal tools, with a key you can revoke. For a public site, connect from your own server, which keeps the key secret, and forward the articles to your users.
How it differs from a server client
- The key goes in the URL. Browsers cannot set headers on a WebSocket, so use
?apiKey=instead of thex-api-keyheader. - You cannot see why a connection was refused. The browser does not show the HTTP status of a refused connection. The socket just closes with code
1006before it opens. A wrong key, a plan without WebSockets and a full connection limit all look the same. Stop after a few failed attempts in a row and check the key and plan in the dashboard. - Everything else is the same. Send the subscribe message, ping every 25 seconds, handle the control frames and reconnect when needed. See Lifecycle & limits.
Connection URLs
| Stream | URL |
|---|---|
| Enriched | wss://wss.finlight.me?apiKey=YOUR_API_KEY |
| Raw | wss://wss.finlight.me/raw?apiKey=YOUR_API_KEY |
Optional query parameters: takeover=true replaces your stalest connection when you are at your limit, and clientVersion=... labels your client. URL-encode the values. See Connect.
Complete example
This client:
- connects with the key in the URL and sends the subscribe message,
- pings every 25 seconds and reconnects when no pong arrives for 60 seconds,
- reconnects with a wait that grows from 1 to 30 seconds, and resets the wait after a pong or an article,
- stops after 5 refused connections in a row, after
VALIDATION_FAILEDand after aconnection_limitpreemption, - waits one hour after a
quota_exceededpreemption, - drops duplicate frames, also the initial push after a reconnect,
- reconnects after 115 minutes, before the 2 hour limit. This leaves a short gap. Fill it through REST if you need every article; see Lifecycle & limits.
It reads both the v3 frames and the v2 control frames the server sends before the first subscribe.
Browser client
const API_KEY = 'YOUR_API_KEY' // tests only, see the note above
const BASE_URL = 'wss://wss.finlight.me' // raw stream: 'wss://wss.finlight.me/raw'
const SUBSCRIBE = {
payloadVersion: 3,
query: 'ticker:AMD',
language: 'en',
include: ['companies', 'events'], // leave out on the raw stream
includeUpdates: true,
clientNonce: crypto.randomUUID(),
}
function startStream({ onArticle, onStatus = console.log }) {
let ws
let pingTimer
let watchdog
let rotateTimer
let delay = 1000
let refusedInARow = 0
let stopped = false
const seen = new Set()
const resetWatchdog = () => {
clearTimeout(watchdog)
watchdog = setTimeout(() => ws.close(4000, 'no pong'), 60_000)
}
const stop = (why) => {
stopped = true
onStatus(`stopped: ${why}`)
ws?.close(1000)
}
const scheduleReconnect = (waitMs) => {
onStatus(`reconnecting in ${Math.round(waitMs / 1000)} s`)
setTimeout(connect, waitMs)
}
function connect() {
if (stopped) return
let opened = false
let nextWait = null // set by frames that need a special wait
ws = new WebSocket(`${BASE_URL}?apiKey=${encodeURIComponent(API_KEY)}`)
ws.onopen = () => {
opened = true
refusedInARow = 0
ws.send(JSON.stringify(SUBSCRIBE))
pingTimer = setInterval(() => ws.send(JSON.stringify({ action: 'ping', t: Date.now() })), 25_000)
rotateTimer = setTimeout(() => {
nextWait = 0
ws.close(1000, 'rotate')
}, 115 * 60_000)
resetWatchdog()
}
ws.onmessage = (message) => {
const frame = JSON.parse(message.data)
const name = frame.event ?? frame.action // v2 control frames use "action"
const data = frame.data ?? frame
switch (name) {
case 'article.created':
case 'article.updated': {
delay = 1000
resetWatchdog()
const key = `${name}|${data.id}|${JSON.stringify(data)}`
if (seen.has(key)) return
seen.add(key)
if (seen.size > 5000) seen.delete(seen.values().next().value)
onArticle(name, data)
break
}
case 'connection.pong':
case 'pong':
delay = 1000
resetWatchdog()
break
case 'connection.admitted':
case 'admit':
onStatus(`admitted, lease ${data.leaseId}`)
break
case 'connection.preempted':
case 'preempted':
if (data.reason === 'connection_limit') stop('another connection took over')
else nextWait = 60 * 60_000 // quota_exceeded: try again in one hour
break
case 'connection.error':
if (data.code === 'VALIDATION_FAILED') stop(`subscribe rejected: ${JSON.stringify(data.details)}`)
else onStatus(`server error ${data.code}: ${data.message}`)
break
default:
// "error" in v2 form, or an event this client does not know yet
onStatus(`ignored frame ${name}`)
}
}
ws.onclose = (event) => {
clearInterval(pingTimer)
clearTimeout(watchdog)
clearTimeout(rotateTimer)
if (stopped) return
if (!opened && ++refusedInARow >= 5) {
stop('connection refused 5 times: check the API key and your plan')
return
}
if (event.code === 1008) {
stop('closed by the server with code 1008')
return
}
const wait = nextWait ?? delay
delay = Math.min(delay * 2, 30_000)
scheduleReconnect(wait)
}
}
connect()
return { close: () => stop('closed by you') }
}
// Usage
const stream = startStream({
onArticle: (event, article) => console.log(event, article.id, article.title),
})
// later: stream.close()
Messages you will see
| Frame | Meaning |
|---|---|
connection.admitted | Your first subscribe arrived. It is sent before the server checks the subscribe. |
article.created | A new matching article. The first one right after the subscribe is the newest existing match. |
article.updated | A change to a matching article. Only with includeUpdates: true. |
connection.pong | The answer to your ping. |
connection.preempted | The server closes this connection. Check reason. |
connection.error | A problem with your message. Check code. |
{"action": ...} | A control frame in the v2 form, sent before your first subscribe. |
See Frames for the full list and the error codes.
What's next
- Subscribe: every subscribe field.
- Raw stream: the faster skeleton stream.
- Lifecycle & limits: ping, rotation, quota and gap filling.