admin-plugins author calendar category facebook post rss search twitter star star-half star-empty

Tidy Repo

The best & most reliable WordPress plugins

Fetch in Node.js: A Practical Guide for Web Requests

Fetch in Node.js: A Practical Guide for Web Requests

Ethan Martinez

November 5, 2026

Blog

Use the built-in fetch() in Node.js for most HTTP requests. It is clean, familiar, and now part of modern Node, so many apps no longer need extra request libraries for basic API calls. Node.js lists fetch as a browser-compatible global API, which means the same style works on the server and in the browser [source: Node.js].

TLDR: Node.js fetch() lets you make HTTP requests with a simple promise-based API. For example, a small service that calls a payments API 10,000 times per day can use fetch() without adding Axios or another package. Use await fetch(url), check response.ok, then parse data with response.json(). Add AbortController for timeouts, because hanging requests are a real pain.

What fetch does in Node.js

fetch() sends web requests from your Node app. You can call REST APIs, send JSON, download files, or talk to internal services. If you have used fetch in the browser, the Node version will feel familiar.

Here is the basic shape:

const response = await fetch('https://api.example.com/users');
const users = await response.json();

console.log(users);

That is the big win. No setup. No import in modern Node. No heavy wrapper. Just call the URL and handle the response.

A simple GET request

A GET request is the most common case. You ask an API for data, wait for the response, then parse it.

async function getUser(id) {
  const response = await fetch(`https://api.example.com/users/${id}`);

  if (!response.ok) {
    throw new Error(`Request failed: ${response.status}`);
  }

  return response.json();
}

const user = await getUser(42);
console.log(user.name);

The annoying part: fetch() only rejects on network errors. A 404 or 500 does not throw by itself. It drives me crazy that this still catches people out. Always check response.ok or response.status.

Sending JSON with POST

POST requests are used when you send data. For APIs, that usually means JSON.

async function createUser() {
  const response = await fetch('https://api.example.com/users', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      name: 'Maya',
      role: 'admin'
    })
  });

  if (!response.ok) {
    throw new Error(`Create failed: ${response.status}`);
  }

  return response.json();
}

The headers tell the server what you are sending. The body must be a string for JSON, so use JSON.stringify(). Simple, but easy to forget when moving fast.

Handling timeouts

fetch() does not take a normal timeout option. Expect to waste time on this once if you come from other libraries. The standard way is AbortController.

async function fetchWithTimeout(url, options = {}, timeoutMs = 5000) {
  const controller = new AbortController();

  const timer = setTimeout(() => {
    controller.abort();
  }, timeoutMs);

  try {
    const response = await fetch(url, {
      ...options,
      signal: controller.signal
    });

    return response;
  } finally {
    clearTimeout(timer);
  }
}

Now you can prevent a request from hanging forever:

const response = await fetchWithTimeout(
  'https://api.example.com/reports',
  {},
  3000
);

In real apps, this matters. If 2% of external requests hang for 30 seconds, your workers can pile up fast. A 3-second timeout keeps the app moving and makes failures easier to track.

Common response types

Most examples use response.json(), but that is not your only option.

  • response.json() parses JSON from an API.
  • response.text() reads plain text, HTML, or logs.
  • response.arrayBuffer() handles binary data.
  • response.blob() exists too, though it is more common in browser code.

Pick the method that matches the response. If you call json() on non-JSON text, your code will throw.

Headers, tokens, and auth

APIs often need an auth token. Add it in the headers.

const response = await fetch('https://api.example.com/account', {
  headers: {
    Authorization: `Bearer ${process.env.API_TOKEN}`,
    Accept: 'application/json'
  }
});

Keep secrets in environment variables. Do not hard-code tokens in your source files. That mistake can turn into a long afternoon of key rotation and awkward messages.

Practical error handling

A good wrapper can save repeated code. Keep it small. Do not build a giant client until you need one.

async function requestJson(url, options) {
  const response = await fetchWithTimeout(url, options, 5000);

  if (!response.ok) {
    const message = await response.text();
    throw new Error(`HTTP ${response.status}: ${message}`);
  }

  return response.json();
}

This gives you status checks, timeout handling, and JSON parsing in one place. It also returns useful error messages instead of vague failures.

When fetch is enough

Use built-in fetch() when you need simple HTTP calls, JSON APIs, webhooks, or internal service requests. It is great for small services, scripts, serverless functions, and backend routes.

You may still want a library if you need automatic retries, request caching, complex interceptors, upload progress, or advanced client features. But for many apps, plain fetch() is enough. Start there. Add more only when the code proves it needs more.

Best practices

  • Always check response.ok. Bad status codes do not throw.
  • Use timeouts. Slow APIs should not freeze your app.
  • Parse carefully. Match json(), text(), or binary methods to the response.
  • Keep tokens out of code. Use environment variables.
  • Wrap repeated logic. A tiny helper beats copy-pasted checks.

fetch() in Node.js is practical, readable, and good enough for a lot of web request work. The main trick is not the request itself. It is handling failure, timeouts, and response parsing like you mean it.