Back to results for “HTTP & Web Servers”
Node.js › HTTP & Web Servers

How would you create a basic HTTP server in Node.js using only the built-in node:http module, without any framework?

Beginner

Answer

The http.createServer() function accepts a callback (or request listener) invoked for every incoming request, receiving request (req) and response (res) objects -- req provides details about the incoming request (method, url, headers), while res is used to construct and send the response (setting headers, writing the body, and calling res.end() to finish the response).
const http = require('node:http');

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello, World!');
});

server.listen(3000, () => console.log('Server running on port 3000'));
Real-world example A minimal internal health-check service uses the raw http module directly rather than a full framework like Express, since its single, extremely simple responsibility (returning a 200 status) doesn't justify the additional dependency and abstraction overhead of a framework.

Common follow-ups: At what point does a project's growing complexity typically justify introducing a framework like Express over the raw http module?;What does res.writeHead() do differently from simply setting individual headers with res.setHeader()?