How to Handle JSON Requests and Responses in a Node.js Server
JSON is the standard API format. Here is how to handle it in a Node.js server.
How to Handle JSON Requests and Responses in a Node.js Server
JSON is the standard API format. Here is how to handle it in a Node.js server.
Reading JSON Request Bodies
The request body is a stream. For JSON, listen to 'data' for chunks, concatenate, and JSON.parse on 'end'. In Express, use express.json() middleware which does this automatically.
Sending JSON Responses
Set Content-Type to application/json with response.writeHead(200, { 'Content-Type': 'application/json' }), then send JSON.stringify(data) with response.end.
Handling Invalid JSON
If JSON.parse fails, the body is not valid JSON. Catch the error and send a 400 Bad Request response. Express's json middleware does this automatically, returning 400 for invalid JSON.
Large JSON Bodies
For very large JSON, use streaming JSON parsers instead of loading the entire body into memory. This keeps memory low for large payloads.
Content-Type Checking
Check the Content-Type header to confirm it is application/json before parsing as JSON. This prevents errors when the client sends a different format.
The Takeaway
Handle JSON in Node.js by reading the body stream and parsing with JSON.parse, sending responses with Content-Type application/json and JSON.stringify, handling invalid JSON with a 400, using streaming parsers for large bodies, and checking Content-Type. Express's json middleware automates most of this.
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.
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.
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.
Ready to master Node.js completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master Node.js
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

