Node.js JSON Responses
JSON is a serialized representation, not a JavaScript object traveling directly over the network. Send the appropriate content type and a bounded public shape.
How it works
Choose the fields a client is allowed to receive instead of serializing an internal record wholesale. The fixture includes a private note in its server-side record but projects only id and name into the response. JSON.stringify does not make a value safe for every HTML or script context; this example delivers an application/json response. A real endpoint also needs its own authentication, caching and schema policy.
Run the code
Run this example locally with Node.js. The exact sources are reviewed on Node 22.15.1 and Node 24.22.1 unless a specialised lab states otherwise. Save the complete source as json-response.mjs in a separate empty exercises folder and run node json-response.mjs. There is no Node.js browser runner on Bhylu; the plain JavaScript playground does not provide these filesystem, server or process APIs.
Download the complete source. Ordinary Node scripts need no Apache, PHP or MySQL service. File examples own their temporary folders; network fixtures use loopback and available temporary ports.
Example
import http from 'node:http';
import { once } from 'node:events';
const record = { id: 701, name: 'tripod', internalNote: 'fictional staff note' };
const server = http.createServer((request, response) => {
response.writeHead(200, {
'content-type': 'application/json; charset=utf-8',
'cache-control': 'no-store',
});
response.end(JSON.stringify({ id: record.id, name: record.name }));
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const base = 'http://127.0.0.1:' + server.address().port;
try {
const response = await fetch(base);
const body = await response.json();
console.log(response.headers.get('content-type').startsWith('application/json'));
console.log(Object.keys(body).join(','));
} finally {
server.closeAllConnections();
await new Promise((resolve, reject) =>
server.close((error) => (error ? reject(error) : resolve())),
);
}
Expected result
true id,name
The response has a declared JSON representation and omits the internal field. Projection is useful even in a tiny fixture because internal data structures tend to grow over time without every API client needing the new fields.
Use the Node.js API reference for the precise version contract.