Fetching JSON with fetch()
The fetch() API is the modern, built-in way to make HTTP requests in the browser and Node.js. To get JSON, call fetch() and then .json() on the response, which reads the body and runs JSON.parse() for you:
fetch("https://api.example.com/users/1")
.then((response) => response.json())
.then((data) => console.log(data.name))
.catch((error) => console.error("Request failed:", error));Using async/await (recommended)
async/await makes the same code far easier to read and to wrap in try/catch:
async function getUser(id) {
try {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status} - ${response.statusText}`);
}
const user = await response.json();
return user;
} catch (error) {
console.error("Could not load user:", error.message);
return null;
}
}Sending JSON in a POST Request
To send JSON, set the Content-Type header and stringify the body with JSON.stringify():
const response = await fetch("https://api.example.com/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Ada", role: "admin" }),
});
const created = await response.json();Need this as a cURL command or in another language? Paste it into cURL to Code or test the endpoint in the API Request Playground.
Handling Errors Properly (response.ok)
This is the single most common mistake: fetch does not reject on HTTP errors. A 404 or 500 still resolves successfully — only a network failure rejects the promise. Always check response.ok:
const response = await fetch(url);
if (!response.ok) {
// 404, 500, etc. land here — fetch did NOT throw
throw new Error(`Request failed with status ${response.status}`);
}
const data = await response.json();Why response.json() Can Throw
response.json() calls JSON.parse() under the hood, so if the server returns HTML (an error page) or an empty body, you get SyntaxError: Unexpected token '<'. See our guide on the Unexpected token in JSON error. Guard against empty responses:
const text = await response.text();
const data = text ? JSON.parse(text) : null;Fetching JSON in Node.js
fetch is built into Node.js 18 and later — no node-fetch package needed:
// Node.js 18+
const res = await fetch("https://api.example.com/data");
const data = await res.json();Frequently Asked Questions
Does fetch parse JSON automatically?
No. You must call await response.json() (or .text()) to read and parse the body.
Why doesn't fetch throw on a 404?
By design — fetch only rejects on network errors. Check response.ok or response.status yourself.
How do I send JSON with fetch?
Set headers: { "Content-Type": "application/json" } and body: JSON.stringify(data).
When a response looks malformed, drop it into the JSON Formatter or JSON Validator to find the problem, and see how to parse JSON in JavaScript for more on JSON.parse.