JavaScript Fetch API Cheat Sheet

The JavaScript fetch() API

Download as .pdf

API: /api/v1/cheatsheet/javascript-fetch-api-cheat-sheet

1. Basic GET Request

javascript

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
fetch("https://api.bytestaq.com/data")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(err => console.error(err));

// Async/Await
async function getData() {
  try {
    const res = await fetch("https://api.bytestaq.com/data");
    const data = await res.json();
    console.log(data);

  } catch (err) {
    console.error(err);
  }
}

2. Response Handling

javascript

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const res = await fetch(url);

res.ok        // true if status 200–299
res.status    // HTTP status code
res.headers   // headers object
Body Parsers
await res.json()
await res.text()
await res.blob()
await res.arrayBuffer()

3. POST Request (JSON)

javascript

1
2
3
4
5
6
7
8
9
fetch("https://api.bytestaq.com/users", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    name: "Alice"
  })
});

4. PUT / PATCH / DELETE

javascript

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// PUT
fetch(url, {
  method: "PUT",
  body: JSON.stringify(data)
});

// PATCH
fetch(url, {
  method: "PATCH",
  body: JSON.stringify(data)
});

// DELETE
fetch(url, {
  method: "DELETE"
});

5. Headers

javascript

1
2
3
4
5
6
fetch(url, {
  headers: {
    "Authorization": "Bearer TOKEN",
    "Content-Type": "application/json"
  }
});

6. Auth Patterns

javascript

1
2
3
4
5
6
7
8
9
// Bearer Token
headers: {
  Authorization: `Bearer ${token}`
}

// Basic Auth
headers: {
  Authorization: "Basic " + btoa("user:pass")
}

7. Sending Form Data

javascript

1
2
3
4
5
6
7
const formData = new FormData();
formData.append("file", file);

fetch(url, {
  method: "POST",
  body: formData
});

Don’t set Content-Type manually (browser sets boundary)


8. Sending URL-Encoded Data

javascript

1
2
3
4
5
6
7
const params = new URLSearchParams();
params.append("key", "value");

fetch(url, {
  method: "POST",
  body: params
});

9. Timeout (via AbortController)

javascript

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const controller = new AbortController();

setTimeout(() => controller.abort(), 5000);

fetch(url, { signal: controller.signal })
  .catch(err => {
    if (err.name === "AbortError") {
      console.log("Request timed out");
    }
  });

10. Error Handling Nuance

fetch only rejects on network errors, not HTTP errors.

javascript

1
2
3
4
5
const res = await fetch(url);

if (!res.ok) {
  throw new Error(`HTTP error: ${res.status}`);
}

11. Query Parameters

javascript

1
2
3
4
const url = new URL("https://api.bytestaq.com");
url.searchParams.set("q", "test");

fetch(url);

12. Cookies & Credentials

javascript

1
2
3
fetch(url, {
  credentials: "include" // send cookies
});

Options:

  • "omit" (default)
  • "same-origin"
  • "include"

13. CORS Basics

javascript

1
2
3
fetch(url, {
  mode: "cors"
});

Controlled by server headers (Access-Control-Allow-Origin) Client cannot override server restrictions


14. Streaming Response

javascript

1
2
const res = await fetch(url);
const reader = res.body.getReader();

Used for:

  • large files
  • real-time data streams

15. Retry Pattern

javascript

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
async function fetchWithRetry(url, retries = 3) {
  try {
    return await fetch(url);
  } catch (err) {
    if (retries > 0) {
      return fetchWithRetry(url, retries - 1);
    }
    throw err;
  }
}

16. Full Example

javascript

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
async function request(url, options = {}) {
  const res = await fetch(url, {
    headers: {
      "Content-Type": "application/json",
      ...options.headers
    },
    ...options
  });

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

  return res.json();
}

17. Common Patterns

javascript

1
2
3
4
5
6
7
8
9
// Parallel Requests
const [a, b] = await Promise.all([
  fetch(url1).then(r => r.json()),
  fetch(url2).then(r => r.json())
]);

// Sequential
const a = await fetch(url1);
const b = await fetch(url2);

18. Common Mistakes

  • Forgetting await res.json()
  • Not checking res.ok
  • Setting wrong Content-Type
  • Not handling timeouts
  • CORS confusion (server-side issue)

19. Quick Reference

javascript

1
2
3
4
5
6
7
fetch(url, {
  method: "GET | POST | PUT | DELETE",
  headers: {},
  body: JSON.stringify(data),
  credentials: "include",
  signal
});

Join the Newsletter

Practical insights on Django, backend systems, deployment, architecture, and real-world development — delivered without noise.

Get updates when new guides, learning paths, cheat sheets, and field notes are published.

No spam. Unsubscribe anytime.



There is no third-party involved so don't worry - we won't share your details with anyone.