How do I send a JSON response in Node.js?
Set Content-Type to application/json with response.writeHead(200, { 'Content-Type': 'application/json' }), then send JSON.stringify(data) with response.end.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in How to Handle JSON Requests and Responses in a Node.js Server
The request body is a stream. Listen to 'data' for chunks, concatenate, and JSON.parse on 'end'. In Express, use express.json() middleware which does this automatically.
Catch JSON.parse errors and send a 400 Bad Request response. Express's json middleware does this automatically, returning 400 for invalid JSON, so you do not need to handle it manually.
For very large JSON, use streaming JSON parsers instead of loading the entire body into memory with JSON.parse. This keeps memory low for large payloads that would otherwise cause memory issues.
Still have questions?
Browse all our FAQs or reach out to our support team
