The core of a Node.js HTTP transaction is a request listener function that receives a request object and a response object. You create it with http.createServer(), and the listener runs once per incoming request. Everything else—reading the body, setting headers, sending the response—happens inside that function.
The Request Listener: Your Main Entry Point
When you call http.createServer(), you pass it a function. That function is called once for every request the server receives. It receives two arguments:
- req (an
IncomingMessage): contains the request method, URL, headers, and the request body as a readable stream. - res (a
ServerResponse): lets you set status codes, headers, and write the response body.
Here is the minimal skeleton:
const http = require('http');
const server = http.createServer((req, res) => {
// handle the request
});
server.listen(3000);
That listener is the heart of the transaction. It runs for every request, so all logic—routing, reading data, sending responses—lives inside it.
Reading the Request: Method, URL, and Headers
Inside the listener, you can inspect the request immediately. The most useful properties are:
req.method– a string like'GET'or'POST'.req.url– the path and query string, e.g.'/users?id=42'.req.headers– an object with all request headers, lowercased. For example,req.headers['content-type'].
You can use these to route requests. A simple router might look like:
if (req.method === 'GET' && req.url === '/') {
res.end('Home page');
} else if (req.method === 'POST' && req.url === '/users') {
// handle POST
} else {
res.statusCode = 404;
res.end('Not Found');
}
Note that req.url includes the query string. If you need the path only, you can use new URL(req.url, 'http://localhost') to parse it.
Reading the Request Body: It’s a Stream
The request body is not available as a single string. It arrives as a stream of chunks. To read it, you listen to the 'data' and 'end' events, or use a helper like for await...of.
The most common pattern is to accumulate chunks into an array and then concatenate them:
let body = [];
req.on('data', (chunk) => {
body.push(chunk);
});
req.on('end', () => {
body = Buffer.concat(body).toString();
// body is now the full request body as a string
});
Why an array? Because chunk is a Buffer, and concatenating buffers with + would convert them to strings prematurely. Using Buffer.concat(body) keeps the data as binary until you decide to decode it.
If the request is JSON, you would then parse it:
const data = JSON.parse(body);
Always handle the case where the body might be empty or malformed. Wrap JSON.parse in a try/catch and respond with a 400 status if it fails.
Sending the Response: Status, Headers, and Body
The response object (res) is where you control what the client receives. The order of operations matters:
- Set the status code (default is 200).
- Set headers.
- Write the body.
- End the response.
Here’s a complete example:
res.statusCode = 201;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ ok: true }));
You can also use res.write() multiple times before res.end(), but for most cases a single res.end() with the full body is simpler.
Important: res.end() must be called exactly once per request. Forgetting it leaves the client hanging. If you use an early return, make sure every code path ends the response.
Error Handling: What Can Go Wrong
Several things can go wrong during a transaction. Here are the main ones and how to handle them:
- Client aborts the request – If the client disconnects mid-request, the
reqemits an'aborted'event. You should stop processing and clean up. - Stream errors – The request body stream can emit an
'error'event. Attach a listener to avoid an uncaught exception. - Response errors – If the socket breaks while writing,
resemits an'error'event. Listen for it and log it. - Unhandled exceptions – Wrap your request handler in try/catch and send a 500 status if something unexpected happens.
Here’s a pattern that covers the basics:
const server = http.createServer((req, res) => {
req.on('aborted', () => console.log('request aborted'));
req.on('error', (err) => {
console.error(err);
res.statusCode = 400;
res.end('Bad Request');
});
res.on('error', (err) => console.error(err));
try {
// your logic
} catch (err) {
console.error(err);
res.statusCode = 500;
res.end('Internal Server Error');
}
});
Note that if the request has already ended, calling res.end() again will throw. Guard against that by checking res.writableEnded.
Putting It All Together: A Worked Example
Let’s build a small server that echoes back the JSON it receives. This shows the full lifecycle:
const http = require('http');
const server = http.createServer((req, res) => {
// Only accept POST requests
if (req.method !== 'POST') {
res.statusCode = 405;
res.setHeader('Allow', 'POST');
res.end('Method Not Allowed');
return;
}
// Read the body
let body = [];
req.on('data', (chunk) => body.push(chunk));
req.on('end', () => {
const raw = Buffer.concat(body).toString();
let parsed;
try {
parsed = JSON.parse(raw);
} catch (err) {
res.statusCode = 400;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ error: 'Invalid JSON' }));
return;
}
// Respond with the parsed data
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ received: parsed }));
});
});
server.listen(3000, () => {
console.log('Listening on port 3000');
});
If you run this and send a POST request with a JSON body, you’ll get back the same object wrapped in received. If you send invalid JSON, you get a 400 error.
To test it, you can use curl:
curl -X POST -H "Content-Type: application/json" -d '{"name":"Ada"}' http://localhost:3000
That should return .
Common Pitfalls and How to Avoid Them
Here are the mistakes that trip up most beginners:
- Forgetting to call
res.end()– The client will wait forever. Make sure every code path ends the response. - Setting headers after writing the body – Once you call
res.write()orres.end(), headers are sent. You cannot change them afterward. Set headers before writing. - Using
req.urlwithout parsing – It includes the query string. If you compare it to a path, usenew URL(req.url, 'http://localhost').pathname. - Not handling stream errors – An unhandled
'error'event onreqwill crash the process. Always attach an error listener. - Assuming the body is complete in one chunk – It rarely is. Always accumulate chunks.
If you follow the patterns above, you’ll avoid these issues.
When to Use a Framework Instead
Node’s built-in http module gives you full control, but it is verbose. For a production API, you might prefer a framework like Express or Fastify. They handle routing, body parsing, and error handling for you.
However, understanding the raw transaction is still valuable. It helps you debug issues, understand what frameworks do under the hood, and write minimal servers for small tasks.
If you’re just starting, build a few raw servers first. Once you’re comfortable with the request/response cycle, pick a framework for convenience.