News API in JavaScript and Node.js
In Node.js 18 or newer you can call World News API with the built-in fetch: send GET https://api.worldnewsapi.com/search-news with your key in the x-api-key header, and you get up to 100 articles per request for 1 point plus 0.01 points per article. Keep that call on a server, because a key in browser code is readable by every visitor. This guide builds a search script, a 50-line proxy with node:http that your front end can call, and an async pager, for about 8 points in total.
- Runtime: Node.js 18+ (global
fetch,URL,AbortSignal.timeout). No npm packages needed. - Authentication:
x-api-keyheader (recommended) orapi-keyquery parameter. - Key handling: server side only. The terms make you responsible for charges caused by a leaked key.
- Paging:
number1 to 100 per request,offsetto move forward. - Free plan limits: 1 request per second and 1 request at a time, so no
Promise.allover pages.
What you'll build
search.mjs: one search request that prints titles and the points it used.server.mjs: a proxy onhttp://localhost:3000/api/newsthat adds your key, allows only known parameters and caps the page size, so your browser code never sees the key.paginate.mjs: an async generator that walks through results 100 at a time, retries 429 and respects the free plan's rate limit.
Prerequisites
- Node.js 18 or newer (
node --version). - A free API key from the console, with your email address confirmed. The free API key guide explains the limits.
Step 1: Store your key in an environment variable
export WORLD_NEWS_API_KEY="YOUR_API_KEY"
node --version Step 2: Search news with fetch
Save this as search.mjs and run node search.mjs. The .mjs extension allows top-level await.
const API_KEY = process.env.WORLD_NEWS_API_KEY ?? 'YOUR_API_KEY';
const since = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
const url = new URL('https://api.worldnewsapi.com/search-news');
url.search = new URLSearchParams({
text: 'earthquake',
language: 'en',
'earliest-publish-date': since,
number: '10',
}).toString();
const response = await fetch(url, { headers: { 'x-api-key': API_KEY } });
if (!response.ok) {
throw new Error(`World News API returned HTTP ${response.status}`);
}
const data = await response.json();
console.log(`${data.available} matching articles`);
for (const article of data.news) {
console.log(article.publish_date, article.title, article.url);
}
console.log('Points used:', response.headers.get('X-API-Quota-Request'));
console.log('Points left today:', response.headers.get('X-API-Quota-Left')); Example response (shortened), from the Search News docs for text=earth+quake&language=en&earliest-publish-date=2024-04-01. Your results will be newer.
{
"offset": 0,
"number": 10,
"available": 83,
"news": [
{
"id": 206030983,
"title": "Nearly 30 aftershocks recorded around NJ quake epicenter since Friday",
"text": "New Jersey continues to shake after Friday’s 4.8-magnitude earthquake ...",
"url": "https://nypost.com/2024/04/06/us-news/nearly-30-aftershocks-recorded-around-nj-quake-epicenter/",
"publish_date": "2024-04-06 22:44:18",
"authors": ["Deirdre Bardolf"],
"category": "environment",
"language": "en",
"source_country": "us",
"sentiment": -0.545
}
]
} Every article also carries summary, image and video. All filters are listed in the Search News reference; the Python guide has a table of the common ones.
Step 3: Keep the key out of the browser
Anything you ship to a browser is public. A visitor can read the key from your JavaScript bundle or from the request headers in the developer tools in a few seconds. Build tools that inline environment variables into client code, for example variables prefixed VITE_ or NEXT_PUBLIC_, publish them the same way.
The terms ask you to keep the key confidential and make you responsible for misuse and any additional charges if it leaks. On the free plan a leaked key burns your 50 daily points, and you get 402 errors until midnight UTC. On a paid plan it can run up overage charges. So the browser calls your server, and only your server calls World News API.
Step 4: Build a small proxy with node:http
Save this as server.mjs. It accepts GET /api/news, copies only the parameters in ALLOWED, caps number at 20 so one visitor request costs at most 1.2 points, adds the key and passes the API's status code and JSON back.
import http from 'node:http';
const API_KEY = process.env.WORLD_NEWS_API_KEY;
const PORT = Number(process.env.PORT ?? 3000);
const ALLOWED = new Set([
'text', 'language', 'source-country', 'categories', 'entities',
'earliest-publish-date', 'latest-publish-date', 'sort', 'sort-direction', 'offset', 'number',
]);
const MAX_NUMBER = 20; // 1 point + 20 * 0.01 = 1.2 points per request at most
if (!API_KEY) {
console.error('Set WORLD_NEWS_API_KEY before starting the proxy.');
process.exit(1);
}
function sendJson(res, status, body) {
res.writeHead(status, { 'content-type': 'application/json' });
res.end(JSON.stringify(body));
}
const server = http.createServer(async (req, res) => {
let incoming;
try {
incoming = new URL(req.url, 'http://localhost');
} catch {
sendJson(res, 400, { error: 'bad request' }); // a malformed request line must not crash the server
return;
}
if (req.method !== 'GET' || incoming.pathname !== '/api/news') {
sendJson(res, 404, { error: 'not found' });
return;
}
const upstream = new URL('https://api.worldnewsapi.com/search-news');
for (const [name, value] of incoming.searchParams) {
if (ALLOWED.has(name)) upstream.searchParams.set(name, value);
}
const number = Math.max(1, Math.min(Number(upstream.searchParams.get('number')) || 10, MAX_NUMBER));
upstream.searchParams.set('number', String(number));
try {
const apiResponse = await fetch(upstream, {
headers: { 'x-api-key': API_KEY },
signal: AbortSignal.timeout(30_000),
});
res.writeHead(apiResponse.status, {
'content-type': apiResponse.headers.get('content-type') ?? 'application/json',
});
res.end(await apiResponse.text());
} catch {
sendJson(res, 502, { error: 'news request failed' }); // the proxy's own error, e.g. a timeout
}
});
server.listen(PORT, () => {
console.log(`Proxy running: http://localhost:${PORT}/api/news?text=climate&language=en`);
}); Start it with node server.mjs and open the printed URL. Your front end then calls the proxy with a relative URL and never sees the key:
// Browser code: no key here, the proxy adds it. Serve the page from the same origin as the proxy and load
// this in a <script type="module"> (it uses top-level await).
const response = await fetch('/api/news?text=climate&language=en&number=10');
if (!response.ok) {
throw new Error(`News request failed with HTTP ${response.status}`);
}
const { news } = await response.json();
for (const article of news) {
if (!/^https?:\/\//.test(article.url)) continue; // only web links, never javascript: URLs
const link = document.createElement('a');
link.href = article.url;
link.textContent = article.title; // textContent, not innerHTML: titles are untrusted text
document.body.append(link, document.createElement('br'));
} Two things to add before the proxy goes public. First, put it behind your own login or a per-visitor rate limit: anyone who finds /api/news can spend your points. Second, check the terms before you add a response cache. They allow caching of user-requested data only with prior written permission and for at most 1 hour.
Step 5: Page through results
Save this as paginate.mjs. searchPages() yields one page of up to 100 articles at a time, waits 1 second between requests, and retries 429 up to 5 times with delays of 2 to 32 seconds plus jitter.
const API_KEY = process.env.WORLD_NEWS_API_KEY ?? 'YOUR_API_KEY';
const BASE_URL = 'https://api.worldnewsapi.com';
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function getJson(path, params) {
const url = new URL(`${BASE_URL}/${path}`);
url.search = new URLSearchParams(params).toString();
for (let attempt = 0; ; attempt++) {
const response = await fetch(url, {
headers: { 'x-api-key': API_KEY },
signal: AbortSignal.timeout(30_000),
});
if (response.status === 429 && attempt < 5) {
await sleep(2 ** (attempt + 1) * 1000 + Math.random() * 1000);
continue;
}
if (response.status === 402) {
throw new Error('402: daily points used up, the quota resets at midnight UTC');
}
if (!response.ok) {
throw new Error(`HTTP ${response.status} from ${path}`);
}
return response.json();
}
}
async function* searchPages(filters, maxResults = 300) {
let offset = 0;
while (offset < maxResults && offset <= 10_000) {
const number = Math.min(100, maxResults - offset);
const page = await getJson('search-news', { ...filters, offset, number });
const news = page.news ?? [];
if (news.length === 0) return;
yield news;
offset += news.length;
if (offset >= page.available) return;
await sleep(1000); // free plan: 1 request per second, 1 at a time
}
}
const since = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
let total = 0;
for await (const news of searchPages({
text: 'electric vehicles',
language: 'en',
'earliest-publish-date': since,
sort: 'publish-time',
'sort-direction': 'DESC',
})) {
total += news.length;
console.log(`+${news.length} articles (total ${total}), first: ${news[0].title}`);
} Pages are fetched one after the other on purpose. With Promise.all you would send several requests at once, and the free plan answers the extra ones with 429. If you sort by publish-time, set text or both publish dates; otherwise the API limits the range to the last 31 days.
Error handling
| Status | What it means | What to do |
|---|---|---|
| 401 Unauthorized | Listed for every endpoint in the OpenAPI file; the docs say nothing more. | Check that the proxy really has WORLD_NEWS_API_KEY set and that the header name is x-api-key. |
| 402 Payment Required | On the free plan, today's points are used up (quota docs). | Stop and show a "try again later" message. The quota resets at midnight UTC. |
| 429 Too Many Requests | Too many requests per second or at the same time for your plan. | Retry with growing delays and send requests one at a time. |
| 400 | Invalid parameters, for example more than 10 news-sources. | Fix the request. Retrying will not help. |
The proxy passes these status codes through unchanged, so your front end can handle them the same way.
What this guide costs
| Step | Requests | Points |
|---|---|---|
| Step 2: one search, 10 results | 1 | 1.1 |
| Step 4: one proxy call, 10 results | 1 | 1.1 |
| Step 5: 300 articles | 3 | 6 |
| Total | 5 | 8.2 of the free plan's 50 daily points |
Next steps
- Prefer a typed client? The JavaScript and TypeScript SDKs are on the SDK page (
npm install worldnewsapi). - Show a country's top stories with Top News (1 point per request).
- Turn any news site into a feed with Website to RSS.
- Give an LLM current, cited news: news data for RAG.
- Compare providers before you commit: news API comparison.
Frequently asked questions
Can I call World News API directly from browser JavaScript?
You should not. The key would be visible to anyone who opens your page's source or network tab, and the terms make you responsible for charges caused by a misused key. Call the API from a server or serverless function and let the browser call that.
Which Node.js version do I need?
Node.js 18 or newer. fetch, URL, URLSearchParams and AbortSignal.timeout are built in, so the examples need no npm packages.
Is there an npm package for World News API?
Yes, the worldnewsapi package, listed on the SDK page together with a TypeScript client. This guide uses plain fetch, which works the same in any Node.js 18+ project.
How do I page through news results in JavaScript?
Request up to 100 articles with the number parameter, then repeat with offset increased by the number of articles you received until you have enough or reach the available count. On the free plan, send the pages one after the other, 1 second apart.
Last updated November 22, 2026 by the World News API team. Spotted an error? Tell us at [email protected] or on Discord.
More from World News API
- Compare news APIs
World News API next to NewsAPI.org, NewsData.io, GNews, Mediastack and others. - Guides
Step-by-step tutorials with working code. - Use cases
AI agents, finance, media monitoring and research. - Documentation
Every endpoint with parameters, examples and quotas.