node:http Serves JSON Without A Framework
Serve JSON with node:http createServer alone: listen(0) takes a free ephemeral port and close releases the handle so the process exits.
Code
import { createServer } from 'node:http';
const server = createServer((req, res) => {
// writeHead sets status and headers first; res.end writes the body
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({ status: 'ok', path: req.url }));
});
// Port 0 asks the OS for a free ephemeral port instead of a fixed one
server.listen(0, '127.0.0.1', () => {
const { port } = server.address();
console.log('listening:', port > 0);
// Closing frees the handle so the process can exit on its own
server.close(() => console.log('closed cleanly'));
});Output
Captured from a sandboxed run of this snippet in the build pipeline.
listening: true
closed cleanlyWhat the code does
node:http supplies createServer — built-in surface, no package involved.
Top-level bindings server hold the demo state — nothing sits inside a function scope.
What to watch for
- The dependency surface is just
node:http, and that one is built into Node.js.
Applying it
Expect labeled output — listening:, closed cleanly — when the file runs.
Statements that matter
res.end(JSON.stringify({ status: 'ok', path: req.url }));
server.listen(0, '127.0.0.1', () => {
const { port } = server.address();
console.log('listening:', port > 0);
// Closing frees the handle so the process can exit on its own
server.close(() => console.log('closed cleanly'));
});
Interactive Tools for This Topic
Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
FAQ
- Is the imported module an npm package?
- No — `node:http` is built into Node.js. The `node:` prefix marks core modules, so there is nothing to add to a project.
Report a problem with this exampleOpens a pre-filled issue on GitHub.