Official React hooks SDK for the Newsdata.io News
API. Drop-in useNews, useLatestNews, useArchiveNews, useCryptoNews,
useMarketNews, useNewsCount, … hooks plus a <NewsDataProvider> to share
one client. Built on the same proven core as the Node client — validation,
typed errors, retries with exponential backoff — and ships first-class
TypeScript definitions.
Zero runtime dependencies, no build step, React 18+ as a peer dependency.
npm install newsdataapi
# react is a peer dependency
npm install reactimport { NewsDataProvider, useLatestNews } from 'newsdataapi';
function Headlines() {
const { data, error, isLoading } = useLatestNews({
q: 'bitcoin',
country: ['us', 'gb'],
language: 'en',
});
if (isLoading) return <p>Loading…</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<ul>
{data.results.map((article) => (
<li key={article.article_id}>
<a href={article.link}>{article.title}</a>
</li>
))}
</ul>
);
}
export default function App() {
return (
<NewsDataProvider apiKey={process.env.REACT_APP_NEWSDATA_API_KEY}>
<Headlines />
</NewsDataProvider>
);
}The API has two versions. v2 is the current one; the v1 hooks keep working unchanged.
| Hook | Endpoint | Notes |
|---|---|---|
useNews(params) |
/2/news |
Latest news, or historical with from_date / to_date |
useMarket(params) |
/2/market |
Market / financial news |
useCrypto(params) |
/2/crypto |
Cryptocurrency news |
useSources(params) |
/2/sources |
Available sources (single page) |
useCountNews(params) |
/2/count/news |
Aggregate news counts |
useCountMarket(params) |
/2/count/market |
Aggregate market counts |
useCountCrypto(params) |
/2/count/crypto |
Aggregate crypto counts |
useNewsStream(registrationId) |
wss://ws.newsdata.io/ws/event |
Real-time stream (below) |
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 responses carry total_results
and next_page where v1 carries totalResults and nextPage.
const { data, error, isLoading } = useNews({
q_in_title: 'tesla',
source_url: 'bbc.com',
content: true,
});
// data.total_results, data.next_pageThere is no /2/archive — useNews covers historical news through
from_date / to_date.
| Hook | Endpoint | Notes |
|---|---|---|
useLatestNews(params) |
/1/latest |
Real-time news |
useArchiveNews(params) |
/1/archive |
Historical news |
useNewsSources(params) |
/1/sources |
Available sources (single page) |
useCryptoNews(params) |
/1/crypto |
Cryptocurrency news |
useMarketNews(params) |
/1/market |
Market / financial news |
useNewsCount(params) |
/1/count |
Aggregate counts (requires from_date, to_date) |
useCryptoCount(params) |
/1/crypto/count |
Aggregate crypto counts |
useMarketCount(params) |
/1/market/count |
Aggregate market counts |
Every hook has the same shape:
const { data, error, isLoading, refetch } = useLatestNews(params, options);data— the API response (nulluntil the first fetch resolves)error— a typedNewsdataError(nullon success)isLoading—truewhile a request is in flightrefetch()— re-run the request; returns the underlyingPromise. Only the newest request (a refetch or a params change) updates the state, so a slow older response never overwrites newer data.
useLatestNews(params, { enabled: false }) // skip the request until enabledoptions.enabled (default true) defers fetching — handy when params aren't
ready (e.g. waiting on user input).
Values can be a single string or an array of strings (sent comma-joined),
and parameter names are case-insensitive — qInTitle and qintitle are
equivalent:
useLatestNews({ country: ['us', 'gb'], language: 'en', size: 20 });Inline param objects are safe — the hook compares by value, not reference, so re-renders only re-fetch when the values change.
The real-time service is part of API v2, so its articles and envelopes use the
v2 layout. useNewsStream opens a real-time connection for a registered
query and accumulates the matching articles. Register the query first — the
returned registration_id identifies it from then on:
import { useEffect, useState } from 'react';
import { useNewsDataClient, useNewsStream } from 'newsdataapi';
function BitcoinTicker() {
const client = useNewsDataClient();
const [registrationId, setRegistrationId] = useState(null);
const [registerError, setRegisterError] = useState(null);
useEffect(() => {
let cancelled = false;
client.websocketRegister({ q: 'bitcoin', language: 'en' })
.then(({ results }) => {
if (!cancelled) setRegistrationId(results.registration_id);
})
.catch((err) => {
if (cancelled) return;
// Already registered (a remount, a page reload, StrictMode): the API
// answers 409 with the existing id, so reuse it.
const existingId = err?.responseBody?.results?.registration_id;
if (existingId) setRegistrationId(existingId);
else setRegisterError(err);
});
return () => { cancelled = true; };
}, [client]);
// A falsy id defers connecting until registration resolves.
const { articles, error, isConnected } = useNewsStream(registrationId);
if (registerError) return <p>Could not register: {registerError.message}</p>;
if (error) return <p>Stream error: {error.message}</p>;
return (
<>
<p>{isConnected ? 'live' : 'connecting…'}</p>
<ul>
{articles.map((a) => <li key={a.id}>{a.title}</li>)}
</ul>
</>
);
}Registrations persist on the account — they are not tied to the component —
and every plan allows only so many. Delete one you no longer need with
websocketDelete(registrationId).
The hook returns { articles, latest, error, isConnected }. Articles
accumulate newest first and are capped at maxArticles (default 100) so a
long-lived stream can't grow without bound; switching to another
registrationId starts from an empty list. The connection opens on mount,
closes on unmount, and reconnects through a capped exponential backoff.
isConnected is true while a connection is open and false while
connecting or reconnecting.
const { articles, latest } = useNewsStream(registrationId, {
enabled: true, // defer connecting when false
maxArticles: 100, // cap on retained articles
reconnect: true, // auto-reconnect on transient drops
});error is set for a permanent rejection — bad API key or unknown registration_id,
exhausted API credits, or too many simultaneous devices — which surfaces as 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. That response is never added to articles: it becomes the 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.
Each delivered article consumes 1 API credit per connected device.
Transient drops reconnect silently and leave error null.
Managing registered queries goes through the client:
websocketRegister(params), websocketFetch(), and
websocketDelete(registrationId).
websocketRegister takes the same filter parameters as news(), under the
same v2 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() returns results as 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). 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.
Outside React, use the same NewsDataApiWebSocket class the hook wraps:
import { NewsDataApiWebSocket } from 'newsdataapi';
const ws = new NewsDataApiWebSocket(client, {
onOpen: () => console.log('connected'), // optional
onClose: ({ code, reason }) => console.log('closed', code, reason), // optional
});
for await (const response of ws.stream(registrationId)) {
console.log(response.results);
}ws.close() ends the stream at once, even while it is waiting to reconnect.
Two ways to wire it up:
// 1. Let the provider construct the client. Options defined outside the
// component (or with useMemo) keep the same identity on every render.
const clientOptions = { timeout: 10_000, maxRetries: 3 };
<NewsDataProvider apiKey="..." options={clientOptions}>
<App />
</NewsDataProvider>
// 2. Or pass your own pre-built client (full control over its lifecycle).
import { NewsDataApiClient } from 'newsdataapi';
const client = new NewsDataApiClient(apiKey);
<NewsDataProvider client={client}>
<App />
</NewsDataProvider>The provider rebuilds the client only when apiKey or an option's value
changes: plain values (timeout, maxRetries, …) compare by value, so an
equal inline options={{ … }} is safe too; functions and objects (fetch,
logger) compare by identity. A rebuilt client refetches every hook and
reopens every stream.
Anywhere inside the provider you can grab the client directly:
import { useNewsDataClient } from 'newsdataapi';
function ExportButton() {
const client = useNewsDataClient();
return <button onClick={() => client.archiveApi({ q: 'x' }).then(save)}>Export</button>;
}All hook errors are instances of the typed hierarchy from the core SDK:
import {
NewsdataValidationError, NewsdataAuthError, NewsdataRateLimitError,
NewsdataApiError, NewsdataNetworkError,
} from 'newsdataapi';
if (error instanceof NewsdataRateLimitError) {
console.log('retry after', error.retryAfter, 'seconds');
}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)
Validation errors are raised before the request is sent (no API quota
spent) — e.g. setting q and qInTitle together, an unsupported parameter
for that endpoint, or missing from_date/to_date on a v1 count endpoint.
They reject the returned promise (with paginate: true, the first iteration
throws them); a client method never throws synchronously.
A 429 that can be waited out is retried: the client sleeps for Retry-After
plus one second (or the exponential backoff when there is no header). When
Retry-After is longer than retryBackoffMax (default 60 s) it rejects at
once with NewsdataRateLimitError and retryAfter set, leaving the wait to
you. In the browser, Retry-After is readable only if the API exposes it
through CORS (Access-Control-Expose-Headers); otherwise it reads as missing
and the backoff applies.
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. 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.
You can also use the underlying client without React — same surface as
newsdata-nodejs-client:
import { NewsDataApiClient } from 'newsdataapi';
const client = new NewsDataApiClient(apiKey, { timeout: 10_000 });
// scroll: follow nextPage cursors and merge.
const merged = await client.latestApi({ q: 'news', scroll: true, maxResult: 200 });
// paginate: async generator, one page at a time.
for await (const page of client.latestApi({ q: 'news', paginate: true, maxPages: 5 })) {
console.log(page.results.length);
}2.0.0 changed the default baseUrl from https://newsdata.io/api/1/ to
https://newsdata.io/api: endpoint paths now carry the API version
(1/latest, 2/news, …). If you passed baseUrl: 'https://newsdata.io/api/1/'
(or a proxy URL ending in /1/), drop the /1 — the old value now produces
…/1/1/latest and a 404.
npm install
npm test # node:test, 34 tests, no API key requiredOfficial Newsdata.io clients across languages and runtimes:
- Python — newsdataapi/python-client (PyPI)
- Node.js — newsdataapi/newsdata-nodejs-client (npm)
- PHP — newsdataapi/php-client (Packagist)
- Java — newsdataapi/newsdata-java-sdk (Maven Central)
- .NET — newsdataapi/newsdata-dotnet-sdk (NuGet)
- Go — newsdataapi/newsdata-go-client (pkg.go.dev)
- Dart / Flutter — newsdataapi/newsdata-flutter-client (pub.dev)
- MCP Server (AI assistants) — newsdataapi/newsdata.io-mcp (PyPI)
Also see free news datasets for ML / NLP work.
