agyanadda@gmail.com

Node.js HTTP Module: Create a Web Server

Node.js Core Modules 1 min read Updated Dec 3, 2026 Topic 9 of 30

Node.js can create a web server with the built-in http module — no extra software needed.

createServer

http.createServer((req, res) => { ... }) runs your function for every request.

  • req.method — GET, POST, ...
  • req.url — the path and query, e.g. /users?page=2
  • req.headers — request headers

Sending a response

  • res.statusCode = 200 or res.writeHead(200, { 'Content-Type': 'text/html' })
  • res.setHeader(name, value)
  • res.end(body) — send and finish. Always end the response, or the browser keeps waiting.

Parsing the URL

new URL(req.url, 'http://localhost') gives pathname and searchParams.get('page').

Reading a POST body

The body arrives in chunks: collect them with for await (const chunk of req), then JSON.parse.

Start listening

server.listen(3000) → open http://localhost:3000.

Writing routing by hand gets long quickly — that is why most apps use Express, covered later.

Example

Example — A server with three routes JavaScript
import http from 'node:http';

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

  if (req.method === 'GET' && url.pathname === '/') {
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    return res.end('<h1>Home page</h1>');
  }

  if (req.method === 'GET' && url.pathname === '/api/hello') {
    const name = url.searchParams.get('name') ?? 'Guest';
    res.writeHead(200, { 'Content-Type': 'application/json' });
    return res.end(JSON.stringify({ message: `Hello, ${name}` }));
  }

  if (req.method === 'POST' && url.pathname === '/api/echo') {
    let body = '';
    for await (const chunk of req) body += chunk;
    res.writeHead(201, { 'Content-Type': 'application/json' });
    return res.end(body);
  }

  res.writeHead(404, { 'Content-Type': 'text/plain' });
  res.end('Not found');
});

server.listen(3000, () => console.log('Server running at http://localhost:3000'));

/ shows a heading, /api/hello?name=Asha returns {"message":"Hello, Asha"}, POST /api/echo returns the body you sent, and any other URL returns 404 Not found.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method finishes and sends the response?

Exercise 2 True / False

If you forget res.end(), the browser keeps waiting for a response.

Exercise 3 Fill in the Blank

Start the server on port 3000 with server.___(3000)

Frequently Asked Questions

Not to run it: Node is the web server. In production, Nginx is often placed in front as a reverse proxy for HTTPS, compression and serving static files, while Node handles the app.