http.createServer()

Creates an HTTP server that invokes a handler for each request.

Since Node 0.x Spec ↗

Syntax

http.createServer([options][, requestListener])

Parameters

NameTypeRequiredDescription
options object No Server options such as `keepAliveTimeout` and `maxHeaderSize`.
requestListener function No Handler `(req, res)` added as a listener for the `'request'` event.

Returns

http.Server — A Server instance you call .listen() on.

Examples

import { createServer } from 'node:http';

const server = createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('Hello\n');
});
server.listen(3000);
Output
$ curl localhost:3000
Hello
import { createServer } from 'node:http';

createServer((req, res) => {
  if (req.url === '/health') {
    res.end('ok');
  } else {
    res.statusCode = 404;
    res.end('not found');
  }
}).listen(3000);
Output
$ curl localhost:3000/health
ok

Notes

The handler must always end the response or the connection hangs. Throwing synchronously in the handler can crash the process; wrap async work in try/catch. Frameworks like Express wrap this API.

See also