Site icon JD Bots

How to Create a JSON Response with Response.json() in JavaScript

A card titled Response.json(), labelled JavaScript Basics, showing Response.json(data, { status: 201 }) with the status 201 and the content type application/json.

Response.json(): Build an HTTP response with a JSON body in one call.

Response.json() builds an HTTP response from data in one call: it turns the data into JSON text, sets the Content-Type header to application/json and takes a status code. It’s part of the Fetch API, built into browsers and Node.js.

Every command and output on this page is real, run with Node.js 26.13.1 on macOS.

Syntax

Syntax

Response.json(data, { status: code })

See Response: json() static method on MDN.

Prerequisites

The Example

A response that says a record was saved, with the status code 201, Created. Then three reads: its status, its content type and its body. The file is reply.js.

Step 1: Write the Code

reply.js

const response = Response.json({ message: "Saved" }, { status: 201 });

console.log(response.status);
console.log(response.headers.get("content-type"));
console.log(await response.text());

response.headers.get() reads one header. response.text() reads the body, and await waits for it.

Step 2: Run It

Terminal

node reply.js

Output

201
application/json
{"message":"Saved"}

The status is 201, the content type is application/json, and the body is the object as JSON text.

Common Mistakes

MistakeWhat happensDo this instead
Building it with new Response(JSON.stringify(data))The content type is text/plain;charset=UTF-8, so the body isn’t marked as JSONUse Response.json(data)
Passing the status as a number: Response.json(data, 201)Node.js stops with a TypeErrorPass an object: { status: 201 }

FAQ

Does Response.json() send anything?

No. It only builds the response object. A server, or a framework’s route handler that returns it, sends it to the browser.

Conclusion

Response.json(data, { status }) gives you a JSON response with the right content type in one line.

Additional Resources

JavaScript is a trademark of Oracle Corporation in the United States. Node.js is a trademark of the OpenJS Foundation.

Exit mobile version