How do I check if a request is JSON in Node.js?
Check the Content-Type header: request.headers['content-type'] should be application/json. If it is not, the client sent a different format and parsing as JSON would fail. This prevents errors from format mismatches.
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.
Set Content-Type to application/json with response.writeHead(200, { 'Content-Type': 'application/json' }), then send JSON.stringify(data) with response.end.
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.
Still have questions?
Browse all our FAQs or reach out to our support team
