Skip to content

Instantly share code, notes, and snippets.

@cisoun
Created August 26, 2026 16:54
Show Gist options
  • Select an option

  • Save cisoun/dfd322e46aebd1e29e4d96cc4f05a177 to your computer and use it in GitHub Desktop.

Select an option

Save cisoun/dfd322e46aebd1e29e4d96cc4f05a177 to your computer and use it in GitHub Desktop.
Minimal Node.js server with JSON support
/**
* Minimal Node.js server with JSON support.
*
* Usage: node server.js
* Client: curl -i -d '{}' 127.0.0.1:8000
*
* NOTES:
* - `Request` and `Response` classes can be extended. For instance, you can
* extend `Request` to override `json` function in order to raise a
* specific custom error on parsing failure. You'll need then to reconfigure
* the `IncomingMessage` argument of the `createServer` function.
*/
import {
Buffer
} from 'node:buffer';
import {
createServer,
IncomingMessage,
ServerResponse
} from 'node:http';
class Request extends IncomingMessage {
json () {
return new Promise((resolve, reject) => {
const data = [];
this.on('data', (chunk) => data.push(chunk));
this.on('error', (e) => reject(e));
this.on('end', () => {
try {
resolve(JSON.parse(Buffer.concat(data)));
} catch (e) {
reject(e);
}
});
});
}
}
class Response extends ServerResponse {
json (code, data) {
this.writeHead(code, { 'Content-Type': 'application/json' });
this.end(JSON.stringify(data));
}
}
createServer({
IncomingMessage: Request,
ServerResponse: Response
}, async (req, res) => {
// Circular references.
req.res = res;
res.req = req;
// Handle request.
try {
console.log('Reading body...');
const data = await req.json();
console.log(`Body: ${JSON.stringify(data)}`);
res.json(200, { message: 'ok' });
} catch (e) {
res.json(400, { error: e.message });
};
}).listen(8000, '0.0.0.0', () => {
console.log('listening...');
});
@cisoun

cisoun commented Aug 26, 2026

Copy link
Copy Markdown
Author

Raise a specific error on JSON parsing failure:

class HTTPError extends Error {
	constructor (code, ...args) {
		super(...args);
		this.code = code;
	}
}

class CustomRequest extends Request {
	async json () {
		try {
			return await super.json();
		} catch (e) {
			throw new HTTPError(415, 'Invalid payload');
		}
	}
}

createServer({
	IncomingMessage: CustomRequest,
	ServerResponse: Response
}, async (req, res) => {
	try {
		const data = await req.json();
	} catch (e) {
		if (e instanceof HTTPError) {
			res.json(e.code, { error: e.message });
		}
	}
}).listen(8000);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment