Node.js HTTP Server

Create a web server with the http module.

✍️ 2 exercises in this lesson

Node can create a web server with no framework:

  1. http.createServer((req, res) => { ... })
  2. Read req.method and req.url.
  3. Set headers with res.writeHead(status, headers) and send a body with res.end().
  4. server.listen(3000)

In practice, frameworks like Express make routing much easier.

Key Takeaways: Node.js HTTP Server

Mastering Node.js HTTP Server helps you write clean and reliable Node.js code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Node.js HTTP Server Code Example

Node.js
import http from "node:http";

const server = http.createServer((req, res) => {
  if (req.url === "/") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end("<h1>Home</h1>");
  } else if (req.url === "/api/time") {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ time: new Date().toISOString() }));
  } else {
    res.writeHead(404);
    res.end("Not found");
  }
});

server.listen(3000, () => console.log("Server on http://localhost:3000"));
Output
Server on http://localhost:3000
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

Node.js HTTP Server Practice Exercises

Check what you learned in “Node.js HTTP Server”.

/ 2 solved
Fill in the blank

Create a server with the http module.

const server = http.((req, res) => { });
✓ Correct! Not quite. Try again.
Multiple choice

Which method sends the response body and finishes the response?

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services