Skip to content
jshacks.dev
APIs

Send JSON with fetch POST

Send a JSON body with fetch POST by stringifying the object and setting the Content-Type header, since fetch does not do either of those for you.

1 min read
Summarize in AI

Passing an object as body sends the text [object Object]. The body must be a string, and the server needs the content type to parse it.

post-json.jsJavaScript
const res = await fetch('https://httpbin.org/post', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Ada', role: 'admin' }),
});

const result = await res.json();
console.log(result.json);
console.log(result.headers['Content-Type']);
Text
{ name: 'Ada', role: 'admin' }
application/json

JSON.stringify turns the object into a string. Without the Content-Type: application/json header, the request is sent as text/plain and most frameworks will not parse the body. The httpbin.org/post endpoint echoes what it received, so you can see both. See Supplying request options.

Values such as undefined, functions, Date objects and BigInt need care: dates become ISO strings and BigInt throws. A cross-origin POST with this header triggers a CORS preflight request.

Also inBrowser
Taggedfetch
Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
Browser

Find the closest ancestor with closest

Walk up from an element to the nearest ancestor that matches a selector with closest, which includes the element itself. Works in all modern browsers.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.