Node.js HTTP server example

node-js

Updated August 29, 2026

Node's built-in node:http module is enough for a minimal HTTP server. Save this as server.mjs (or set "type": "module" in package.json):

import { createServer } from 'node:http';

const server = createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/') {
    res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' });
    res.end('Hello from Node.js\n');
    return;
  }

  res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
  res.end('Not found\n');
});

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

Run it with node server.mjs and stop it with Ctrl-C. Binding to 127.0.0.1 keeps this example local; use a deliberate host and a reverse proxy for a deployed service. A real application should validate request bodies, set appropriate headers, handle errors, and shut down gracefully. Frameworks add routing and middleware, but the underlying server still needs sensible limits and logging.

Sources

related.

Ruslan Osipov

Ruslan Osipov

About the author