The http Module

Node's built-in http module powers web servers and clients.

Syntaxconst http = require('http');

The built-in http module lets you build web servers and make HTTP requests β€” no external library required. It is the foundation that frameworks like Express are built on.

What a server does

A server listens on a port for incoming requests. For each request it receives a request object (what the client wants) and a response object (what you send back).

Example

Example Β· javascript
const http = require('http');

// The simplest possible server
const server = http.createServer((req, res) => {
  res.end('Hello, HTTP!');
});

server.listen(3000, () => {
  console.log('Listening on http://localhost:3000');
});

When to use it

  • A microservice team creates a lightweight internal health-check server using only the built-in `http` module to avoid Express overhead.
  • A developer learning Node.js builds their first web server without any framework to understand how HTTP works at the protocol level.
  • A webhook receiver uses `http.createServer` to listen for POST requests from a third-party payment provider without framework dependencies.

More examples

Minimal HTTP server

The smallest possible HTTP server -- creates, configures, and starts listening in seven lines.

Example Β· js
const http = require('http');

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

server.listen(3000, () => console.log('Listening on :3000'));

Inspect request method and URL

Logs the HTTP method and URL of every incoming request -- the two most important properties of `req`.

Example Β· js
const http = require('http');

http.createServer((req, res) => {
  console.log(`${req.method} ${req.url}`);
  res.writeHead(200);
  res.end();
}).listen(3000);

Send custom headers

Sets individual response headers with `setHeader` and a status code with `writeHead` before sending the body.

Example Β· js
const http = require('http');

http.createServer((req, res) => {
  res.setHeader('X-Powered-By', 'Node.js');
  res.setHeader('Cache-Control', 'no-store');
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ ok: true }));
}).listen(3000);

Discussion

  • Be the first to comment on this lesson.
The http Module β€” Node.js | SoundsCode