Rez Moss

Rez Moss

Digital Reflections: Exploring Tech, Innovation & Ideas

Node.js Web Server Without Express: Routes, JSON and Static Files

Mar 2016

You can build a web server in Node.js with only the built-in http module. http.createServer takes a function that runs for every request, gets a request object (req) and a response object (res), and you call server.listen(port) to start it. No Express, no npm install.

The smallest version is a few lines:

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 at http://localhost:3000/');
});

Save it as server.js, run node server.js and open http://localhost:3000. Every URL returns the same text, because the handler never looks at the request. A real server needs routes, JSON, request bodies and files, so the rest of this post builds that, still with no dependencies. I tested it on Node 22 with curl, and the responses below are from those runs.

Routing by method and path

req.method gives you GET, POST and so on, and req.url gives the path plus the query string. Parse it with the built-in URL class so /api/hello?name=Rez splits cleanly into a path and parameters:

const http = require('node:http');
const fs = require('node:fs/promises');
const path = require('node:path');

const port = process.env.PORT || 3000;

function sendJSON(res, status, data) {
  res.writeHead(status, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(data));
}

async function readBody(req) {
  const chunks = [];
  for await (const chunk of req) chunks.push(chunk);
  return Buffer.concat(chunks).toString('utf8');
}

const server = http.createServer(async (req, res) => {
  const url = new URL(req.url, `http://${req.headers.host}`);

  if (req.method === 'GET' && url.pathname === '/') {
    const html = await fs.readFile(path.join(__dirname, 'public', 'index.html'));
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    res.end(html);
    return;
  }

  if (req.method === 'GET' && url.pathname === '/api/hello') {
    const name = url.searchParams.get('name') || 'World';
    sendJSON(res, 200, { message: `Hello, ${name}!` });
    return;
  }

  if (req.method === 'POST' && url.pathname === '/api/echo') {
    try {
      const data = JSON.parse(await readBody(req));
      sendJSON(res, 201, { received: data });
    } catch {
      sendJSON(res, 400, { error: 'invalid JSON' });
    }
    return;
  }

  sendJSON(res, 404, { error: 'not found' });
});

server.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

Each route ends with return. Without it, the code would fall through to the 404 at the bottom and try to send a second response, which Node rejects with an error about headers already being sent.

JSON responses and query strings

The sendJSON helper sets the status, the Content-Type: application/json header and the body in one place. Clients and browsers rely on that header to know how to read the response:

$ curl 'localhost:3000/api/hello?name=Rez'
{"message":"Hello, Rez!"}

$ curl localhost:3000/api/hello
{"message":"Hello, World!"}

Reading a POST body

Node doesn’t hand you the request body as one value. req is a stream, and the body arrives in chunks. readBody collects them with for await and joins them into a string, then the route parses it. A body that isn’t valid JSON gets a 400 instead of crashing the server:

$ curl -i -X POST localhost:3000/api/echo -d '{"id":1}'
HTTP/1.1 201 Created
{"received":{"id":1}}

$ curl -i -X POST localhost:3000/api/echo -d 'nope'
HTTP/1.1 400 Bad Request
{"error":"invalid JSON"}

(I trimmed the other headers from the curl -i output.) JSON.parse throws on bad input, so the try/catch is required, not optional. Node.js JSON: parse, stringify, read and write covers the other ways JSON goes wrong.

Unknown paths get the 404 at the end of the handler:

$ curl -i localhost:3000/missing
HTTP/1.1 404 Not Found
{"error":"not found"}

Serving an HTML file

The / route reads public/index.html from disk and sends it with a text/html content type. path.join(__dirname, ...) builds the path from the script’s own folder, so the server finds the file no matter which directory you start it from:

$ curl -i localhost:3000/
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
<h1>Hello from a file</h1>

This serves one fixed file. Be careful if you extend it to serve any path from the URL: a request for /../server.js must not escape the public folder. That’s the point where a small static-file library, or Express’s express.static, earns its place. The fs calls used here are covered in working with files in Node.js.

Running it while you edit

node --watch server.js restarts the server whenever you save a file, so you don’t need nodemon for this. Set the port with an environment variable, PORT=8080 node server.js, which is also what most hosting platforms expect.

The plain http module is a good fit for small APIs, webhooks and tools. Once you have many routes, middleware and validation, a framework saves you from writing your own router. Either way, the handler is a callback that Node calls once per request, the pattern explained in Node.js callbacks.

comments powered by Disqus