Skip to content

About

Official Node.js client (SDK) for the Newsdata.io News API — fetch real-time, historical, crypto, and stock-market news via REST with validation, retries, pagination, and typed errors

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

21 Commits

Folders and files

Repository files navigation

Newsdata.io logo

Newsdata.io Node.js Client

npm version npm downloads CI Node License OpenAPI

Official Node.js client for the Newsdata.io News API. It wraps every endpoint (latest, archive, sources, crypto, market, count, crypto/count, market/count) with client-side parameter validation, automatic retries with exponential backoff, scroll/paginate helpers, and a typed error hierarchy. It also covers the real-time WebSocket service end to end with NewsDataApiWebSocket: register, list, and delete queries, and stream the matching news as it is published.

Zero runtime dependencies — uses the built-in fetch and WebSocket (Node 22+).

Installation

npm install newsdata-nodejs-client

Quickstart

import { NewsDataApiClient, NewsdataError } from 'newsdata-nodejs-client';

const client = new NewsDataApiClient(process.env.NEWSDATA_API_KEY);

try {
  const res = await client.latestApi({
    q: 'bitcoin',
    country: ['us', 'gb'], // string or array of strings
    language: 'en',
  });
  for (const article of res.results) {
    console.log(article.title, '-', article.link);
  }
} catch (err) {
  if (err instanceof NewsdataError) console.error(err.message);
}

CommonJS:

const { NewsDataApiClient } = await import('newsdata-nodejs-client');

Endpoints

The API has two versions. v2 is the current one; the v1 methods keep working unchanged.

v2

Method Endpoint Notes
news(params) /2/news Latest news, or historical with from_date / to_date
market(params) /2/market Market / financial news
crypto(params) /2/crypto Cryptocurrency news
sources(params) /2/sources Available sources (single page)
countNews(params) /2/count/news Aggregate news counts
countMarket(params) /2/count/market Aggregate market counts
countCrypto(params) /2/count/crypto Aggregate crypto counts
websocketRegister(params) /2/websocket/register Register a real-time query
websocketFetch() /2/websocket/fetch List registered queries
websocketDelete(id) /2/websocket/delete Delete a registered query

v2 renames the filter vocabulary to snake_case and folds the four domain filters into two:

v1 v2
qInTitle, qInMeta q_in_title, q_in_meta
excludecountry, excludecategory, excludelanguage exclude_country, exclude_category, exclude_language
domain, domainurl, excludedomain, excludedomainurl source_url, exclude_source_url
prioritydomain source_priority
full_content content
removeduplicate, excludefield remove_duplicate, exclude_field

coin and market_id keep their names. v2 also accepts rawQuery on every endpoint, sources included.

v2 responses carry total_results and next_page where v1 carries totalResults and nextPage; scroll merges under whichever pair the endpoint uses.

const res = await client.news({
  q_in_title: 'tesla',
  source_url: 'bbc.com',
  content: true,
});
console.log(res.total_results, res.next_page);

There is no /2/archive — news() covers historical news through from_date / to_date.

v1

Method Endpoint Notes
latestApi(params) /1/latest Real-time news
archiveApi(params) /1/archive Historical news
sourcesApi(params) /1/sources Available sources (single page)
cryptoApi(params) /1/crypto Cryptocurrency news
marketApi(params) /1/market Market / financial news
countApi(params) /1/count Aggregate counts (requires from_date, to_date)
cryptoCountApi(params) /1/crypto/count Aggregate crypto counts (requires dates)
marketCountApi(params) /1/market/count Aggregate market counts (requires dates)

The real-time service is v2 only — there are no v1 WebSocket methods.

Each params value may be a single value or an array (arrays are sent comma-separated). Parameter names are case-insensitive. See the Newsdata.io documentation — or the OpenAPI 3.1 spec — for the full parameter reference per endpoint.

Pagination

Endpoint methods return a Promise by default. Two opt-in modes:

// scroll: follow nextPage cursors, resolve to one merged response.
const merged = await client.latestApi({ q: 'news', scroll: true, maxResult: 200 });

// paginate: async generator, one response per page.
for await (const page of client.latestApi({ q: 'news', paginate: true, maxPages: 5 })) {
  process(page.results);
}

scroll and paginate are mutually exclusive. With paginate: true the method returns an AsyncGenerator; otherwise it returns a Promise.

Raw query

await client.latestApi({ rawQuery: 'q=bitcoin&country=us&language=en' });

rawQuery is mutually exclusive with all other parameters and is validated against the endpoint's allowed keys; for the v1 count endpoints it must also carry from_date and to_date.

Real-time news (WebSocket)

The real-time service is part of API v2. Register a query first — the returned registration_id identifies it from then on:

import { NewsDataApiClient, NewsDataApiWebSocket } from 'newsdata-nodejs-client';

const client = new NewsDataApiClient('YOUR_API_KEY');
const ws = new NewsDataApiWebSocket(client);

const { results } = await ws.websocketRegister({ q: 'bitcoin', language: 'en' });
const registrationId = results.registration_id;

websocketRegister takes the same filter parameters as news(), under the same names (q, q_in_title, country, exclude_country, source_url, content, exclude_field, timezone, …) — the date, paging and sorting filters, id and url don't apply to a standing query. Registering an identical query twice rejects with a NewsdataApiError whose statusCode is 409; the existing id is at err.responseBody.results.registration_id.

websocketFetch() lists every registered query: results is an array with one entry per query, carrying its registration_id, the filters it was registered with (query), how many devices are streaming it now (active_clients) and when one last connected (last_used, UTC). websocketDelete(id) removes one. Once every registration the plan allows is in use, registering another rejects with a 429 NewsdataRateLimitError carrying the code RegistrationLimitExceeded; it is not retried, since only deleting a registration frees a slot.

Then stream. Each response has status, total_results and results keys, and its articles carry the same v2 layout as news() results (id, url, published_at, …, with related fields grouped under media, source and ai); the registration's exclude_field and timezone apply to them:

for await (const response of ws.stream(registrationId)) {
  for (const article of response.results) {
    console.log(article.title, '-', article.url);
  }
}

Break out of the loop to stop; the connection closes either way. ws.close() ends an in-flight stream from outside the loop — at once, even while it is waiting to reconnect.

Transient drops (network errors, server restarts, abnormal closes) are reconnected automatically with a capped exponential backoff. Pass reconnect: false to stop on the first disconnect instead. A permanent rejection — bad API key or unknown registration_id, exhausted API credits, or too many simultaneous devices — throws NewsdataWebSocketAuthError and is not retried.

When it refuses a connection, the server accepts the handshake, sends one error response — {"status":"error","results":{"message":"…","code":"…"}} — and closes. The stream never yields that response: it becomes the thrown error, whose message is the server's explanation, code its error code and responseBody the whole response. Close code 1008 is permanent; its reason is the bare code: Unauthorized or InvalidRequest (bad key or unknown registration_id), ApiLimitExceeded or ApiKeyLimitExceeded (credits used up), DeviceLimitExceeded (more than 5 devices on one registration_id). Every other close code — 1011 (server error) and 1013 (the client read too slowly) included — is transient and reconnects; with reconnect: false it throws NewsdataWebSocketError carrying the server's message.

Each delivered article consumes 1 API credit per connected device.

Catch it like any other client error:

import {
  NewsdataWebSocketAuthError,
  NewsdataWebSocketError,
} from 'newsdata-nodejs-client';

try {
  for await (const response of ws.stream(registrationId)) {
    // ...
  }
} catch (err) {
  if (err instanceof NewsdataWebSocketAuthError) console.error(`rejected (${err.code}):`, err.message);
  else if (err instanceof NewsdataWebSocketError) console.error('stream error:', err.message);
  else throw err;
}

All connection options are optional:

const ws = new NewsDataApiWebSocket(client, {
  baseUrl: 'wss://ws.newsdata.io/ws/event', // staging / self-hosted / proxied
  reconnect: true,          // auto-reconnect on transient drops; default true
  reconnectDelay: 1000,     // ms before the first reconnect (doubles each retry)
  reconnectDelayMax: 30000, // cap on the reconnect delay
  openTimeout: 10000,       // ms to wait for the opening handshake
  WebSocket: undefined,     // override the implementation (default: global WebSocket)
});

Node 22+. Streaming uses the global WebSocket, which Node ships from v22. On older runtimes pass your own implementation, e.g. new NewsDataApiWebSocket(client, { WebSocket: require('ws') }).

Node's global WebSocket does not expose the handshake HTTP status, so a handshake that fails before the connection opens — a proxy answering 401 or 403, say — shows up as close code 1006 and is retried as a transient failure.

Runnable example: examples/websocket.js.

Client-side validation

Before any request is sent, parameters are validated and normalized. The returned promise rejects with a NewsdataValidationError (without spending API quota; with paginate: true the first iteration throws it — a client method never throws synchronously) when:

  • a parameter is not accepted by that endpoint;
  • mutually-exclusive parameters are set together — q/qInTitle/qInMeta, country/excludecountry, category/excludecategory, language/excludelanguage, domain/domainurl/excludedomain;
  • size is outside 1–50;
  • sentiment_score is set without sentiment;
  • a count endpoint is missing from_date or to_date.

Booleans (full_content, image, video, removeduplicate) are coerced to 1 / 0.

Error handling

import {
  NewsdataValidationError,
  NewsdataAuthError,
  NewsdataRateLimitError,
  NewsdataApiError,
  NewsdataNetworkError,
} from 'newsdata-nodejs-client';

try {
  await client.latestApi({ q: 'news' });
} catch (err) {
  if (err instanceof NewsdataValidationError) {/* err.param */}
  else if (err instanceof NewsdataAuthError) {/* 401 / 403 */}
  else if (err instanceof NewsdataRateLimitError) {/* err.retryAfter */}
  else if (err instanceof NewsdataApiError) {/* err.statusCode, err.responseBody */}
  else if (err instanceof NewsdataNetworkError) {/* err.cause */}
}

Hierarchy:

NewsdataError                       (catch-all base)
├── NewsdataValidationError         (.param)
├── NewsdataApiError                (.statusCode, .responseBody)
│   ├── NewsdataAuthError           (401 / 403)
│   ├── NewsdataRateLimitError      (429; .retryAfter)
│   │   ├── NewsdataApiLimitExceededError      (account credits gone)
│   │   └── NewsdataApiKeyLimitExceededError   (this key's cap gone)
│   │   (RegistrationLimitExceeded stays on NewsdataRateLimitError —
│   │    real-time registration slots, not credits)
│   └── NewsdataServerError         (5xx)
├── NewsdataNetworkError            (.cause)
└── NewsdataWebSocketError          (real-time stream)
    └── NewsdataWebSocketAuthError  (policy-violation close 1008)

Configuration

const client = new NewsDataApiClient(apiKey, {
  timeout: 30_000,          // per-request, ms
  maxRetries: 5,            // total attempts (1 = no retry)
  retryBackoff: 2_000,      // base backoff, ms (exponential)
  retryBackoffMax: 60_000,  // cap on a single backoff, ms
  paginationDelay: 1_000,   // delay between pages, ms
  maxResult: null,          // default cap for scroll mode
  maxPages: null,           // default cap for paginate mode
  includeHeaders: false,    // attach responseHeaders to results
  baseUrl: undefined,       // API root, no version segment; staging/proxy
  fetch: undefined,         // inject a custom fetch
  logger: console,          // optional { debug, info, warn }; API key is redacted
});

baseUrl is the API root without a version segment; the default is https://newsdata.io/api and the client adds /1/… or /2/… itself. Before 0.3.0 it included the version (https://newsdata.io/api/1/), so drop the trailing /1/ if you override it.

Retries cover network errors, HTTP 429, and 5xx. timeout covers the whole request, reading the response body included. A 429 waits for its Retry-After (integer seconds or HTTP-date) plus one second; without the header, backoff is exponential. When Retry-After is longer than retryBackoffMax, the call rejects at once with NewsdataRateLimitError and retryAfter set (seconds), leaving the wait to you. Auth and other 4xx errors are never retried.

A 429 that waiting cannot fix is never retried. NewsdataApiLimitExceededError means the account's whole credit pool is exhausted, NewsdataApiKeyLimitExceededError means this one key hit its own cap while the account may still have credits; both subclass NewsdataRateLimitError, so existing catch blocks keep working. RegistrationLimitExceeded is also never retried, but keeps the plain NewsdataRateLimitError class — it is about real-time registration slots, not credits, and is fixed by deleting a registration.

Development

npm test        # node --test, runs offline (no API key required)

Related libraries

Official Newsdata.io clients across languages and runtimes:

Also see free news datasets for ML / NLP work.

License

MIT

About

Official Node.js client (SDK) for the Newsdata.io News API — fetch real-time, historical, crypto, and stock-market news via REST with validation, retries, pagination, and typed errors

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages