Serving JSON
APIs return JSON — stringify data and set the right header.
Syntax
res.setHeader('Content-Type', 'application/json');Most modern servers return data as JSON rather than HTML. To send JSON:
- Convert your data with
JSON.stringify(). - Set the
Content-Typeheader toapplication/json. - Send it with
res.end().
This is the core of building a REST API.
Example
const http = require('http');
const server = http.createServer((req, res) => {
const data = { name: 'Ada', role: 'engineer' };
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
});
server.listen(3000);
// Response body: {"name":"Ada","role":"engineer"}When to use it
- A mobile app backend returns user profile data as JSON from a Node HTTP route so the iOS client can deserialize it with a single `JSON.parse` call.
- An internal microservice posts a JSON payload to another service using `http.request` with `Content-Type: application/json`.
- A webhook handler parses the incoming JSON body from `req` to extract event data before triggering the appropriate business logic.
More examples
Serve a JSON response
Sets the `Content-Type` header to `application/json` and serializes a JS object with `JSON.stringify`.
const http = require('http');
http.createServer((req, res) => {
const data = { user: 'Alice', role: 'admin', active: true };
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(data));
}).listen(3000);Parse incoming JSON body
Buffers the request stream, parses the JSON body, and echoes it back -- the raw equivalent of `express.json()`.
const http = require('http');
http.createServer((req, res) => {
if (req.method !== 'POST') { res.writeHead(405); return res.end(); }
let raw = '';
req.on('data', c => raw += c);
req.on('end', () => {
const body = JSON.parse(raw);
console.log('Received:', body);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ echo: body }));
});
}).listen(3000);Send JSON with http.request
Makes an outgoing POST request with a JSON body using the low-level `http.request` API.
const http = require('http');
const payload = JSON.stringify({ event: 'signup', userId: 7 });
const req = http.request({
hostname: 'localhost', port: 4000,
path: '/events', method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(payload),
},
}, (res) => console.log('Status:', res.statusCode));
req.write(payload);
req.end();
Discussion