Your First HTTP Server
Your first server answers. Rudely, but it answers.
▶ the lesson · narrated sketch video · tap for sound
the intro
An HTTP server listens on a port and answers requests with responses. You can build one in ten lines of Node, and building it by hand once teaches you what frameworks do for you forever.
fun fact ✦
The C10k problem — ten thousand connections at once — is what made nginx famous.
the docs
the deep dive
the ideas behind the video — concepts, diagrams, a walkthrough and the traps to avoid
Every server ever written, from a weekend project to Google, answers the same three questions: which port do I listen on, what do I do when a request arrives, what do I send back. Write those three answers in code and you have a server. A framework is just someone else's phrasing of the same three questions.
listen, handle, respond
key terms
port
A numbered door on one machine. Many programs can listen at once as long as each has its own door.
localhost:3000handler
Your function. It runs once per request and gets the request plus a response to fill.
(req, res) => ...route
The pairing of a method and path with a handler. Raw Node checks these by hand; frameworks map them for you.
GET /cats → listCatsres.end()
The moment you actually answer. Nothing is sent to the client until you end the response.
res.end("hello")how it works
- 1Create the server
http.createServer takes your handler and returns a server object. Nothing is running yet.
- 2Pick a port and listen
server.listen(3000) starts the loop: the process now sits waiting for requests.
- 3Handle the request
Read req.url and req.method, set res.statusCode and headers, then write the body.
- 4Answer, always
Every path through your handler must call res.end, or the client hangs forever.
- 5Test it
Open localhost:3000 or run curl localhost:3000. Same request either way.
the code, explained
a complete server, nothing hidden
side by side
raw node:http
- zero dependencies
- every detail is yours
- the best way to learn
- verbose per route
Express
- routing and middleware included
- five lines to hello world
- what most job code uses
- hides the port/handler plumbing
Forget res.end on one branch and the request never finishes: the browser spins, curl hangs, and nothing errors on your side. A server owes no answer until your code sends one, so audit every branch.
quick answers
Which port should I pick?
In dev, whatever is free: 3000, 5173, and 8080 are conventions. Anything above 1024 needs no admin rights; 80 and 443 do.
Do I need Express?
Not to learn. Build one raw server first and the framework becomes obvious. Use Express or Fastify when routes multiply.
How do two requests at once work on one thread?
Node accepts both connections and interleaves them on the event loop. As long as your handler stays async, neither blocks the other.
quick hits about Your First HTTP Server
short answers · interviews, tips, trivia & hidden gems