← Back to Node.js, page 2

nodejs-0039 · Easy fresher

How do you create a basic HTTP server with Node's http module, and what do req and res give you?

http.createServer takes a handler that receives a request (a readable stream with method, url and headers) and a response (a writable stream). You set a status code and headers, then write the body and call end(). Frameworks such as Express are built on this same pair of objects.

Full answer

http.createServer((req, res) => { ... }) returns a server. The handler runs once for each request.

req (IncomingMessage) is a readable stream:

  • req.method ('GET', 'POST'), req.url (path and query string), req.headers (names in lower case).
  • The body arrives as chunks. For a GET request you can ignore it.

res (ServerResponse) is a writable stream:

  • res.statusCode = 404 or res.writeHead(200, headers) sets the status and headers.
  • res.setHeader('Content-Type', 'application/json') sets one header before the body.
  • res.write(chunk) sends part of the body. res.end(data) sends the last part and finishes the response. If you never call end, the client waits.

Routing is plain code: look at method and the parsed URL (new URL(req.url, 'http://localhost')) and choose what to send. Frameworks add routing, body parsing and middleware, but nothing magic.

Good habits: always send a status code that matches the result (200, 201, 400, 404, 500), set Content-Type, never throw inside the handler without a try/catch, and listen on port 0 in tests so the system picks a free port.

javascript
const http = require('node:http');

const students = [{ id: 1, name: 'Asha' }, { id: 2, name: 'Ravi' }];

const server = http.createServer((req, res) => {
  const url = new URL(req.url, 'http://localhost');

  if (req.method === 'GET' && url.pathname === '/students') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    return res.end(JSON.stringify(students));
  }
  if (req.method === 'GET' && url.pathname === '/hello') {
    res.setHeader('Content-Type', 'text/plain');
    return res.end('Hello ' + (url.searchParams.get('name') || 'student'));
  }
  res.statusCode = 404;
  res.end('Not found');
});

server.listen(0, async () => {
  const base = 'http://127.0.0.1:' + server.address().port;
  for (const path of ['/students', '/hello?name=Meera', '/missing']) {
    const response = await fetch(base + path);
    console.log(path.padEnd(18), response.status, response.headers.get('content-type'), '|', await response.text());
  }
  server.close();
});

The server calls itself with fetch, which is built into Node 18 and later. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): /students 200 application/json | [{"id":1,"name":"Asha"},{"id":2,"name":"Ravi"}] /hello?name=Meera 200 text/plain | Hello Meera /missing 404 null | Not found

Key points

  • The handler gets req (readable) and res (writable).
  • Set status and headers, then end the response.
  • Routing is a decision on method and path.
  • Use port 0 in tests to avoid port clashes.

Common mistakes

  • Forgetting res.end() so the request hangs.
  • Sending a body without a Content-Type header.
  • Using req.url as if it were only the path. It includes the query string.
  • Setting headers after the first write.

Follow-ups

  • How do you read a JSON request body?
  • What is the difference between res.write and res.end?
  • Why does Express exist if http can do this?

Tips

  • Draw req as a readable stream and res as a writable stream.
  • Show routing with method and path, to prove it is plain code.
  • Mention status codes explicitly.