How do you handle a request inside createServer()?
When you call:
import http from 'node:http';
const server = http.createServer((req, res) => {
// Handle the request here
});
server.listen(3000);the (req, res) function is the handler for every incoming request.
Inside it, you decide what to do with this request and what response to send back.
1. What req and res are
req(IncomingMessage) is the request object, everything that came from the client:req.method, the method (GET, POST, PUT, DELETE, etc.)req.url, the path and query parametersreq.headers, the headersreqitself is a Readable Stream you can read the request body from
res(ServerResponse) is the response object you send back to the client:res.statusCode, the response code (200 by default)res.setHeader(name, value), sets headersres.write(data), writes data into the streamres.end([data]), ends the response (you can pass the final data)
2. Example: basic GET request handling
import http from 'node:http';
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Home page');
} else if (req.method === 'GET' && req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('About us');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Page not found');
}
});
server.listen(3000);Here the handler inspects req.method and req.url and returns different responses.
3. Example: handling a POST request (reading the body)
The request body doesn't arrive all at once, it arrives in chunks,
so req works as a stream (Readable Stream):
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/echo') {
let body = '';
req.on('data', chunk => (body += chunk));
req.on('end', () => {
const data = JSON.parse(body);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ youSent: data }));
});
} else {
res.writeHead(404);
res.end();
}
});Node doesn't parse JSON on its own, you read the data stream, collect it into a string, and parse it yourself.
4. Adding headers and statuses
res.statusCode = 201;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ message: 'Created' }));or in one line:
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Created' }));5. Returning HTML, JSON, or files
-
HTML
javascriptres.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); res.end('<h1>Hello</h1>'); -
JSON
javascriptres.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ ok: true })); -
A file (streamed)
javascriptimport { createReadStream } from 'node:fs'; import { pipeline } from 'node:stream'; if (req.url === '/file') { res.writeHead(200, { 'Content-Type': 'text/plain' }); pipeline(createReadStream('file.txt'), res, err => { if (err) console.error(err); }); }
6. What happens during request handling
- The client makes an HTTP request (e.g. a browser opens a page).
- Node accepts the request and calls your
(req, res)callback. - You inspect the path, method, headers, body.
- You build the response, setting the code, headers, and sending the data.
- Node automatically closes the connection (or keeps it open, with keep-alive).
7. The core idea
With
createServer()you get low-level access to the HTTP request and response. It's a "clean" entry point, from there, you decide how to route, what to return, and how to process the data.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.