Go to content
Web development

Send JSON with fetch

When your TypeScript code creates a record through an API, it sends the record as JSON in a POST request. JSON is a text format for data. With Fetch, set the request method to POST, use the Content-Type header to identify the body as JSON, and pass JSON.stringify(payload) as the body.

JSON.stringify prepares the outgoing data; it does not parse the server’s reply. The code handles those as separate steps.

Build the POST request

Store the data to send and the request settings in named variables so you can inspect them:

type NewNote = {
  title: string;
  body: string;
};

const note: NewNote = {
  title: "Meeting notes",
  body: "Send the agenda.",
};

const options: RequestInit = {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(note),
};

const response = await fetch("/api/notes", options);

The method tells the server that the client is sending data. The Content-Type header says the request body contains JSON. JSON.stringify(note) converts the TypeScript object into the text that goes in the body. This uses the same serialization pattern as MDN’s Request JSON example.

Parse a response separately

If the endpoint returns JSON, call response.json() to read the response body and parse it into a JavaScript value:

const result: unknown = await response.json();

This reads the server’s reply; JSON.stringify(note) prepared the outgoing request. MDN says Response.json() parses the response body into a JavaScript value, such as an object, array, string, or number. The result is a JavaScript value, not JSON text.

More in Web development Back to top ↑