Sub topic 1
Your First Request: How fetch() Works
fetch() is the built-in JavaScript function for making HTTP requests. You give it a URL, it sends the request, and it returns a Promise for the server's answer. That's the short version. The details matter, though. The Promise settles in a specific way and at a specific moment, and it settles on its own terms. Most bugs that beginners write with fetch come from misunderstanding these points. This chapter covers how fetch behaves from the moment you call it to the moment your code has data. Later chapters cover the Response object, body reading, and error handling.
Prerequisites
This chapter assumes you are comfortable with:
- JavaScript functions, objects, and template literals.
- Promises,
.then()/.catch(), andasync/await. try/catcherror handling.- Basic HTTP: what a GET request is, what status codes like 200 and 404 mean, and what headers are.
- Opening the browser developer tools and using the Console and Network panels.
To run the examples, use a modern browser console or Node.js 18 or later. The examples call https://jsonplaceholder.typicode.com, a free public test API. It returns fake JSON data and accepts cross-origin requests.
What fetch() Is
fetch() is a global function provided by the environment, not by the JavaScript language itself. Browsers, Node.js (version 18 and up), Deno, Bun, and Cloudflare Workers all provide it. Its signature is:
fetch(resource, options)resourceis what to request: a URL string, aURLobject, or aRequestobject.optionsis an optional object that configures the method, headers, body, and more. A later chapter covers it in detail.
The return value is always a Promise. It resolves to a Response object or rejects with an error. fetch() never returns a response directly, and it never blocks while it waits.
Making Your First Request
Here is a complete GET request written with async/await:
async function getTodo() {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const todo = await response.json();
console.log(todo);
}
getTodo();Running it logs an object like this:
{ userId: 1, id: 1, title: 'delectus aut autem', completed: false }Here is the same request written as a Promise chain:
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => response.json())
.then((todo) => console.log(todo))
.catch((err) => console.error('Request failed:', err));Both versions do the same work, and both contain two asynchronous steps. The first waits for fetch() and the second waits for response.json(). That second wait is the most important idea in this chapter.
Two Stages: Headers First, Body Later
The Promise from fetch() resolves as soon as the response headers arrive. At that point the body may still be downloading. The Response object you receive already knows the status code and headers, but it does not yet hold the body content. Reading the body with .json(), .text(), or similar methods starts a second asynchronous operation, and that operation returns its own Promise.
You can see the two stages by timing them. The /posts endpoint returns 100 posts, enough data to measure:
const start = performance.now();
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
console.log(`Headers after ${Math.round(performance.now() - start)} ms, status ${response.status}`);
const posts = await response.json();
console.log(`Body after ${Math.round(performance.now() - start)} ms, ${posts.length} posts`);The second number is always at least as large as the first. On a slow connection or with a large response, the gap gets wide. This design lets you check the status and headers before you commit to downloading and parsing a large body. You can even cancel the download partway, which a later chapter covers.
fetch() Returns Immediately
Calling fetch() does not pause your program. It starts the request in the background and hands back a pending Promise right away:
const promise = fetch('https://jsonplaceholder.typicode.com/todos/1');
console.log(promise); // Promise {<pending>}
console.log('This runs first'); // logs before any response arrives
promise.then((response) => {
console.log('Response arrived with status', response.status);
});The request has already been sent when fetch() returns. You don't need to call .then() or await to trigger it. This means you can start several requests one after another and then wait for all of them together, which is the basis of the chapter on parallel requests.
What You Can Pass as the Resource
A URL string
A string is the most common choice. Absolute URLs work everywhere. In a browser, relative URLs such as '/api/users' or 'data.json' resolve against the page's base URL, the same way a link's href does:
// On a page at https://shop.example.com/products/list.html
fetch('/api/cart'); // requests https://shop.example.com/api/cart
fetch('details.json'); // requests https://shop.example.com/products/details.jsonNode.js has no page and so no base URL. A relative URL there makes the Promise reject with a TypeError.
A URL object
When a URL has query parameters, build it with the URL class instead of concatenating strings. searchParams handles the encoding for you:
const url = new URL('https://jsonplaceholder.typicode.com/comments');
url.searchParams.set('postId', '1');
url.searchParams.set('q', 'café & croissants'); // encoded safely
console.log(url.href);
// https://jsonplaceholder.typicode.com/comments?postId=1&q=caf%C3%A9+%26+croissants
const response = await fetch(url);
const comments = await response.json();
console.log(comments.length);Without encoding, the & in that search term would split it into a second, bogus parameter.
A Request object
A Request object bundles the URL and options into one value that you can build in one place and send in another:
const request = new Request('https://jsonplaceholder.typicode.com/users/1', {
headers: { Accept: 'application/json' }
});
console.log(request.method); // 'GET'
console.log(request.url); // 'https://jsonplaceholder.typicode.com/users/1'
const response = await fetch(request);
const user = await response.json();
console.log(user.name);If you pass both a Request and an options object, the values in options override the matching values in the Request.
When the Promise Resolves and When It Rejects
The fetch Promise rejects only when no HTTP response arrives at all. A response with an error status still counts as a response. A later chapter is devoted to this point. For now, keep this table in mind:
| Situation | fetch Promise result |
|---|---|
| Server replies 200 OK | Resolves with a Response |
| Server replies 404 Not Found or 500 Server Error | Resolves with a Response (`response.ok` is `false`) |
| DNS lookup fails or the device is offline | Rejects with `TypeError` |
| Browser blocks the response because of CORS | Rejects with `TypeError` |
| URL is malformed, e.g. `'http://'` | Rejects with `TypeError` |
| Request is cancelled with an AbortSignal | Rejects with `AbortError` (a `DOMException`) |
Even a malformed URL produces a rejected Promise. fetch() does not throw synchronously, so a .catch() or a try/catch around the await catches every one of these cases:
async function tryFetch(url) {
try {
const response = await fetch(url);
console.log(url, '->', response.status);
} catch (err) {
console.log(url, '-> rejected:', err.name, err.message);
}
}
await tryFetch('https://jsonplaceholder.typicode.com/todos/1'); // 200
await tryFetch('https://jsonplaceholder.typicode.com/does-not-exist'); // 404, not a rejection
await tryFetch('https://no-such-host.invalid/'); // rejected: TypeErrorWatching Requests in DevTools
Open the Network panel, select the Fetch/XHR filter, and run any example above. Each fetch appears as a row. Click it to see:
- Headers: the request URL, method, status code, request headers, and response headers.
- Response or Preview: the raw and formatted body.
- Timing: how long each phase took, including DNS lookup, connection, waiting for the first byte, and downloading the content.
The Timing tab shows the two stages from the diagram. "Waiting for server response" ends when the headers arrive, which is when your await fetch() resumes. "Content Download" is the time your await response.json() covers.
Common Mistakes
Forgetting the first await
async function broken() {
const response = fetch('https://jsonplaceholder.typicode.com/todos/1'); // missing await
console.log(response.status); // undefined: response is a Promise
}response is the Promise itself, and Promises have no status property. Add await before fetch(...).
Forgetting the second await
async function alsoBroken() {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const todo = response.json(); // missing await
console.log(todo.title); // undefined: todo is a Promise
}.json() is asynchronous too, as the two-stage model explains, so it needs its own await.
Breaking a then chain
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => { response.json(); }) // braces with no return
.then((todo) => console.log(todo)); // logs undefinedAn arrow function with braces returns undefined unless you write return. Either remove the braces or write return response.json();.
Assuming a resolved Promise means success
A resolved fetch Promise means the server answered. It does not mean the answer was good. Calling .json() on a 404 HTML page throws a SyntaxError that hides the real problem. The chapters on the Response object and error handling show the fix: check response.ok first.
Exercise
The code below logs "Got response" and then throws "SyntaxError: Unexpected token '<'". Explain both lines of output in terms of when the fetch Promise resolves. async function load() { const response = await fetch('https://jsonplaceholder.typicode.com/no-such-page'); console.log('Got response'); return response.json(); }
Show answer
The server answered with an HTTP 404 status. Because an HTTP response arrived, the fetch Promise resolved with a Response, and "Got response" was logged. fetch rejects only when no response arrives at all, for example on a network failure. The body of that 404 response is not valid JSON. Here it is an HTML error page, or something else that starts with '<'. When response.json() tried to parse it, its Promise rejected with a SyntaxError.
Exercise
Using a URL object, write code that fetches the posts written by user 3 from https://jsonplaceholder.typicode.com/posts (the API filters by the userId query parameter) and logs how many posts came back. Why is URL better than writing the query string by hand?
Show answer
const url = new URL('https://jsonplaceholder.typicode.com/posts'); url.searchParams.set('userId', '3'); const response = await fetch(url); const posts = await response.json(); console.log(posts.length); // 10. searchParams percent-encodes values automatically, so spaces, '&', '=', and non-ASCII characters in a value can't corrupt the query string or add stray parameters.
Exercise
In what order do the three messages below appear, and why? console.log('A'); fetch('https://jsonplaceholder.typicode.com/todos/1').then(() => console.log('B')); console.log('C');
Show answer
The order is A, C, B. fetch() sends the request and returns a pending Promise right away without blocking, so 'C' logs next. The .then callback runs only after the response headers arrive, which happens after the current synchronous code has finished.