Resources

JavaScript

Fetch requests

Last updated 15 July 2026

  • javascript
  • http
  • fetch

Also known as: fetch api, javascript fetch, http request js, async fetch

Basic GET request

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

Checking for errors

fetch only rejects on network failure — a 404 or 500 still resolves successfully, so you have to check res.ok yourself.

const res = await fetch('/api/users');
if (!res.ok) {
  throw new Error(`Request failed: ${res.status}`);
}
const data = await res.json();

POST with a JSON body

const res = await fetch('/api/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Ada' }),
});

Aborting a request

const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);

try {
  const res = await fetch('/api/slow', { signal: controller.signal });
  clearTimeout(timeout);
} catch (err) {
  if (err.name === 'AbortError') {
    console.log('Request timed out');
  }
}

Browser support

✅ Chrome ✅ Firefox ✅ Safari ✅ Edge. For older environments (or Node < 18), use a polyfill like node-fetch.