Back to results for “HTTP & HTTPS Modules”
Node.js › HTTP & HTTPS Modules

How would you create a basic HTTP server using only Node's built-in node:http module, without a framework like Express?

Beginner

Answer

http.createServer() takes a callback (or listener function) that's invoked for every incoming request, receiving a request object (with method, url, and headers) and a response object used to write the response body and send it back to the client -- this is the low-level foundation that frameworks like Express are built on top of, adding routing, middleware, and other conveniences absent from the raw module.
const http = require('node:http');

const server = http.createServer((req, res) => {
  if (req.url === '/' && req.method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, World!');
  } else {
    res.writeHead(404);
    res.end('Not Found');
  }
});

server.listen(3000, () => console.log('Server running on port 3000'));
Real-world example A lightweight internal health-check service that needs to respond to exactly one simple GET request is built directly on the raw node:http module rather than pulling in Express, since the added routing and middleware capabilities of a full framework aren't needed for such a minimal, single-purpose server.

Common follow-ups: What specific conveniences does Express add on top of this raw http.createServer() foundation?;How would you manually parse the request body from a POST request using only the raw http module, without a framework's body-parsing middleware?