Endpoints
Real-Time Stream
WS
wss://stream.newsfilter.ioA WebSocket connection that receives every new article as soon as it is indexed. Each message is one article object in JSON, with the same fields as in Search.
- The stream has no filters. Filter the articles in the client.
- Only articles indexed while the client is connected are sent. An article can arrive more than once; remove duplicates by
id. - The server sends a ping every 30 seconds and closes connections that do not answer with a pong within 30 seconds. WebSocket clients answer pings automatically. Messages from the client are ignored.
- A connection can drop, for example when the server restarts. Reconnect after a short delay, as the examples below do. Articles indexed while the client is disconnected are not sent later.
Client with reconnect and keep-alive
The client answers the pings of the server automatically. The packages ws and websockets send the pong, so the client needs no code for it.
The client also sends its own ping every 20 seconds. A connection can drop without a close event, for example when a laptop wakes from sleep or a router drops the connection silently. The client then gets no messages and no error, and waits forever. If the pong to its ping does not arrive within 20 seconds, the client closes the connection and reconnects.
npm install ws
import WebSocket from 'ws';
const API_KEY = 'YOUR_API_KEY';
const STREAM_URL = 'wss://stream.newsfilter.io';
const connect = () => {
const socket = new WebSocket(STREAM_URL, {
headers: { Authorization: API_KEY },
});
const connection = { isAlive: true, heartbeat: null };
socket.on('open', () => {
console.log('connected');
connection.heartbeat = setInterval(() => {
if (!connection.isAlive) {
console.log('no pong received, closing');
socket.terminate();
return;
}
connection.isAlive = false;
socket.ping();
}, 20000);
});
socket.on('pong', () => {
connection.isAlive = true;
});
socket.on('message', (data) => {
const article = JSON.parse(data);
console.log(article.publishedAt, article.title);
});
socket.on('error', (error) => {
console.error(error.message);
});
socket.on('close', (code) => {
clearInterval(connection.heartbeat);
console.log('disconnected (' + code + '), reconnecting in 5 s');
setTimeout(connect, 5000);
});
};
connect();