To POST JSON with fetch, set method: "POST", add the header "Content-Type": "application/json", and pass JSON.stringify(data) as the body. Then check response.ok before reading await response.json(), because fetch does not throw on 4xx or 5xx responses.
const response = await fetch("https://api.example.com/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Ada", age: 36 }),
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const created = await response.json();
Everything below was tested in Node.js 18.18 against a small local server that echoes back the Content-Type it received and the parsed body. Browsers behave the same way for all of it except where noted. Node has had fetch built in, without a flag, since version 18.
What each part of the fetch POST does
| Option | Why it's needed | What happens without it |
|---|---|---|
method: "POST" | fetch defaults to GET. | A GET with a body throws TypeError: Request with GET/HEAD method cannot have body. |
"Content-Type": "application/json" | Tells the server how to parse the body. | fetch labels a string body text/plain;charset=UTF-8; many servers then skip JSON parsing. |
JSON.stringify(...) | body must be a string (or Blob, FormData, etc.), not a plain object. | The object is converted to the literal string [object Object]. |
The mistakes, with the real results
Forgetting the Content-Type header
await fetch(url, { method: "POST", body: JSON.stringify({ name: "Ada" }) });
What the test server received:
{"receivedContentType":"text/plain;charset=UTF-8","received":{"name":"Ada"}}
The JSON text arrives intact, but it's labelled as plain text. That default comes from the Fetch Standard: a string body gets the type text/plain;charset=UTF-8. My test server parsed the body regardless of the label, but servers that check the header don't. Express's express.json(), for example, "only looks at requests where the Content-Type header matches" application/json, and otherwise leaves req.body as undefined. A missing header is a common cause of an empty req.body.
Forgetting JSON.stringify
await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: { name: "Ada" },
});
Server response (status 400):
{"error":"invalid JSON","receivedContentType":"application/json","receivedBody":"[object Object]"}
fetch turned the object into a string the only way JavaScript knows by default, String(obj), which is [object Object]. No error appears on the client side; the server just rejects the request.
Assuming fetch throws on HTTP errors
That same 400 response resolved normally. Logging the response showed:
400 false application/json
That's response.status, response.ok and the response Content-Type. MDN states it directly: fetch() rejects "on some errors, but not if the server responds with an error status like 404." response.ok is true only for statuses 200 to 299. For what each code means, see HTTP status codes explained.
When fetch does throw
fetch rejects when no HTTP response arrives. Real errors from the test:
| Situation | Error (Node.js 18) |
|---|---|
| Nothing listening on the port | TypeError: fetch failed with cause.code = ECONNREFUSED |
Timeout via AbortSignal.timeout(1000) | TimeoutError: The operation was aborted due to timeout |
| GET request with a body | TypeError: Request with GET/HEAD method cannot have body. |
response.json() on an empty body | SyntaxError: Unexpected end of JSON input |
In Node, the useful detail of a network failure is in error.cause; the top-level message is always just "fetch failed". Browsers also report network failures as a TypeError, with wording that differs between browsers.
A reusable postJSON helper with error handling and a timeout
async function postJSON(url, payload, { timeoutMs = 10000 } = {}) {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(payload),
signal: AbortSignal.timeout(timeoutMs),
});
if (!response.ok) {
const detail = await response.text();
throw new Error(`HTTP ${response.status}: ${detail}`);
}
return response.json();
}
const user = await postJSON("https://api.example.com/users", { name: "Ada", age: 36 });
Against the test server this printed:
{
receivedContentType: 'application/json',
received: { name: 'Ada', age: 36 }
}
Notes on the choices:
response.text()for errors. Error responses are often HTML or empty, so calling.json()on them throws aSyntaxErrorthat hides the real status. Read the text, then decide.- One read only. A response body is a stream and can be read once. Calling
.text()and then.json()on the same response fails; in Node 18 the error isTypeError: Body is unusable. Useresponse.clone()if you really need both. AbortSignal.timeout()rejects with aTimeoutErrorafter the given milliseconds. fetch has no timeout of its own, so without it a hung server leaves the promise pending. MDN lists it as widely available in browsers since April 2024.- A 204 No Content response has no body; skip
response.json()for it, or it throws.
If await inside a function is new to you, async/await explained covers how the promise chain works.
Browser only: CORS preflight and cookies
Two things change when the code runs on a web page instead of in Node:
- Preflight. A cross-origin POST with
Content-Type: application/jsonisn't a CORS "simple request" (those only allowapplication/x-www-form-urlencoded,multipart/form-dataandtext/plain), so the browser first sends anOPTIONSrequest and only sends your POST if the server's response allows it. Removing the header to avoid the preflight just causes the unparsed-body problem above; fix the server's CORS headers instead. CORS errors explained has the details. - Cookies. By default, fetch sends credentials (cookies) only to the same origin. To send them cross-origin, add
credentials: "include", and the server must explicitly allow credentials.
Sending a form or a file instead of JSON
For a file upload, pass a FormData object as the body and don't set Content-Type yourself: fetch sets multipart/form-data with the correct boundary automatically. Setting the header by hand drops the boundary and breaks the upload. For the Python side of the same task, see Python requests POST JSON.
Frequently asked questions
- Why is req.body empty on my server when I POST JSON with fetch?
- Usually the Content-Type header is missing. With a string body, fetch sends Content-Type: text/plain;charset=UTF-8, and JSON body parsers such as Express's express.json() only parse requests whose Content-Type matches application/json; in Express 5 req.body is then undefined. Add headers: { 'Content-Type': 'application/json' }.
- Does fetch throw an error on a 404 or 500 response?
- No. fetch only rejects when no HTTP response arrives at all, for example a network failure, a refused connection or an aborted request. A 404 or 500 resolves normally with response.ok set to false, so check response.ok or response.status yourself.
- Can I send JSON with a GET request?
- Not with fetch. A GET or HEAD request with a body throws TypeError: Request with GET/HEAD method cannot have body. Put the data in the query string instead, or use POST.
- Do I need JSON.stringify if I set Content-Type to application/json?
- Yes. The header only labels the body; it does not convert it. Passing a plain object as body sends the string [object Object], which no server can parse as JSON.
- Why does my fetch POST trigger an OPTIONS request?
- In a browser, a cross-origin request with Content-Type: application/json is not a CORS simple request, so the browser first sends an OPTIONS preflight to ask the server for permission. The server has to answer it with the right Access-Control-Allow-* headers.