How do you create a basic HTTP server in Node.js without Express?
Use the built-in http module: http.createServer takes a handler with request and response objects, and listen starts it on a port. You set status and headers on the response and finish it with end.
Explain it simply
Express is a helpful layer on top of Node's own http module. Underneath, a server is just a function that runs for every incoming request. It receives a req object (what the client sent) and a res object (what you send back), like a shopkeeper who gets an order slip and hands back a parcel.
Example
const http = require("http");
const server = http.createServer((req, res) => {
if (req.method === "GET" && req.url === "/health") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ status: "ok" }));
return;
}
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not found");
});
server.listen(3000, () => console.log("Listening on 3000"));What Express adds on top, and plain http does not give you:
- Routing by path and method with parameters like
/users/:id. - Body parsing; with plain
httpyou readreqas a stream and join chunks yourself. - Middleware chains and handy helpers like
res.json()andres.status().
Knowing the raw layer helps in interviews, since Express, Fastify and others are all built on it.
What to say in the interview
"http.createServer gives a callback with req and res; I check req.method and req.url, write headers and end the response. Express wraps this with routing, body parsing and middleware."
Common mistakes
- Forgetting
res.end(), so the request hangs. - Sending a body without a Content-Type header.