fetch
Data from a server.
Fetch is how JavaScript asks a server for data. It works in every browser, and in Node too. You give it a web address, and it returns a promise for the response.

- Ask a server for data
- Browsers and Node
- Returns a promise
Fetching JSON
To keep this example self contained, the first lines start a tiny local server that sends back JSON. Then fetch asks it for the users. The response arrives first, with a status code. Then response dot json reads the body, which is also a promise. Run it.
import http from "node:http";
const server = http.createServer((req, res) => {
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify([{ name: "Ana" }, { name: "Ben" }]));
}).listen(3000);
const response = await fetch("http://localhost:3000/users");
console.log("Status:", response.status, response.ok);
const users = await response.json();
console.log(users.map(u => u.name));
server.close();Status: 200 true [ 'Ana', 'Ben' ]
The steps of a request
First, fetch sends the request. Then the response arrives, with a status code like two hundred for o k, or four oh four for not found. Then you read the body, as JSON, or as text. Each step takes time, so each one returns a promise you await.
| key | value |
|---|---|
| await fetch(url) | the response |
| response.status | 200, 404, 500... |
| response.ok | true for 200–299 |
| await response.json() | the data |
Summary
Fetch requests data from a server. Await the response, check its status, then await response dot json. Next, handling fetch errors properly.
Key takeaways- await fetch(url)
- Check response.ok
- await response.json()