How do you call external APIs from Node.js on the server, and how does it compare to fetching in the browser?
Node.js has the same built-in fetch API as the browser (no import needed since Node v21), so the calling code looks almost identical — the difference is in the request headers that get sent.
async function getStationData(station) {
const url = 'https://transport.opendata.ch/v1/locations?query='
+ station;
const response = await fetch(url, {
method: 'GET',
signal: AbortSignal.timeout(10000)
});
if (response.ok) {
return JSON.parse(await response.text());
} else {
throw Error('fetch failed with status: ' + response.status);
}
}
The interface matches the browser, but the outgoing requests are not the same. A browser sends a rich set of headers a real browser carries — a Referer, a full User-Agent (e.g. Firefox), Accept-Language, etc. Node sends a stripped-down set: user-agent: node, no Referer, different Accept values.
That matters in practice because some APIs inspect those headers — to detect bots, vary content, or block requests with no real User-Agent. So a call that works in the browser can behave differently (or be rejected) from Node, and vice versa.
Tip: If a server-side call fails while the same URL works in your browser, suspect the headers. You can set custom headers in the fetch options to imitate what the API expects.