New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› Node.js› Building an HTTP Server

Building an HTTP Server

💻 Node.js

Create a server with the built-in http module and route requests by URL.

Lesson 4 of 9 Tutorial
0 of 9 completed

Before frameworks, Node could already serve HTTP. Understanding the raw module makes Express and similar tools much clearer.

By the end of this lesson you can:
  • Create an HTTP server.
  • Read the method and URL.
  • Return status codes and JSON.

A Minimal Server

The callback runs for every request. It receives a request and a response object.

import { createServer } from "node:http";

const server = createServer((request, response) => {
  response.writeHead(200, { "Content-Type": "text/plain" });
  response.end("Hello from Node");
});

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

Routing

Check the URL path and the method to decide what to send. Always end the response.

const server = createServer((request, response) => {
  if (request.method === "GET" && request.url === "/health") {
    response.writeHead(200, { "Content-Type": "application/json" });
    response.end(JSON.stringify({ status: "ok" }));
    return;
  }

  response.writeHead(404, { "Content-Type": "application/json" });
  response.end(JSON.stringify({ error: "Not found" }));
});

Status Codes

Return 200 for success, 201 for created, 400 for bad input, 404 for missing resources and 500 for unexpected failures.

Tip Set Content-Type before end(). Once the response is sent, headers cannot change.

Practice

  1. Create a server that responds on / and returns 404 elsewhere.
  2. Add a /time route that returns the current time as JSON.
  3. Return 405 for a POST to a GET-only route.

Hands-on exercise

Build a server with:
1. GET / returns plain text 'Home'.
2. GET /status returns JSON with status ok and the current uptime.
3. Anything else returns 404 JSON.

Recap

The http module serves requests with a request and response object. Route on method and URL, and always send a status.

Example

import { createServer } from "node:http";

const server = createServer((request, response) => {
  response.writeHead(200, { "Content-Type": "text/plain" });
  response.end("Hello from Node");
});

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

Exercises

Exercise 1. Two routes Medium
Build a server with:
1. GET / returns plain text 'Home'.
2. GET /status returns JSON with status ok and the current uptime.
3. Anything else returns 404 JSON.
Node.js exercise-1.txt
Expected Output
Home on /, JSON on /status and a 404 elsewhere.

Lesson Nav

Lesson sections