Node.js from scratch: build your first server
In Phase 2 you were the one answering, but by hand, with nc, or with an nginx configuration that said which text to return at each address. In this phase you write the ServerA program that waits for requests and answers them. By extension, the computer it runs on is also called a server.Go to definition: a program of your own that receives each RequestThe message a client sends to a server to ask for something, for example “give me the home page.”Go to definition, reads it and decides what to answer.
It’s the first phase with code. You don’t need to have ever programmed: two of its lessons teach the language from scratch, and every block of code is explained piece by piece.
What changes when you write the code
Section titled “What changes when you write the code”Remember Ana and Luis’s shop from Phase 2. Its nginx had an address, /api/orders, that acted as the APIAPI stands for Application Programming Interface.The way a program offers its services to other programs, that is, what you can ask it for and how it answers. The frontend talks to the backend through an API.Go to definition for the shop’s website. It always answered the same thing, {"orders":[]}, no matter what you sent it. You could send it an order with a POST and get a 200, but nobody saved it: it was a fake API.
A configuration can only choose among the things nginx already knows how to do. With code, the server does whatever you write: save the order, check that the quantity is a number, warn you if the product doesn’t exist. It’s the same HTTP conversation as in Phase 2; what changes is who decides each response.
| With the nginx configuration | With your own code |
|---|---|
| Each address returns a fixed text | The response depends on what comes in the request |
POST /api/orders answers 200 and saves nothing |
POST /orders saves the order and returns its number |
| Odd data gets through without anyone looking at it | You check every piece of data and answer 422 with a clear message |
| If something fails, it’s nginx’s fault | If something fails, it’s your fault, and you find it in your LogA text file where a program writes down what happens, one line for each thing. A web server’s has a line for each request it receives, and it’s the first thing you look at when something fails.Go to definition |
That last row is the price: everything nginx used to decide, you decide now, including what happens when something goes wrong. That’s what lessons 7, “Validation” and 8, “Errors and logs” are about.
If you’ve never programmed
Section titled “If you’ve never programmed”Lessons 2 and 3 are for you. Lesson 2 teaches the JavaScriptThe programming language of web pages, which, with Node.js, is also used outside the browser to write servers. A JavaScript program is text with instructions that run one after another.Go to definition a server needs, starting from the very basics: what a value, a variable or a function is. Lesson 3 adds TypeScriptA language that is JavaScript with types: annotations that say what kind of data goes in each place, such as a number or a piece of text. The editor and the TypeScript checker warn about errors before the program runs, and Node.js runs it by erasing the types.Go to definition, which is JavaScript with types: a way of saying what shape each piece of data has, so the editor warns you about mistakes before you run anything. You’ll only see what the phase uses, always with its real output.
If you already program in JavaScript, for example because you do frontend, you can skip both. Take their final quiz (“Did you get it?”): if you get almost everything right, move on; if not, you’ll know what to review.
What you will build
Section titled “What you will build”By the end of the phase, the shop will have a real API, written by you and running on your computer. This is how it answers a well-formed order and one with an impossible quantity (we captured it with the final version of the project and Node 26, and trimmed some headers with …):
HTTP/1.1 201 Createdcontent-type: application/jsonlocation: /orders/1…
{"id":1,"productId":2,"quantity":3,"status":"pending"}HTTP/1.1 422 Unprocessable Entitycontent-type: application/json…
{"error":"The data is not valid","details":[{"field":"quantity","problem":"At least 1"}]}The first one creates order number 1, three mugs, and its location header says where to look it up: /orders/1. The second one asked for zero: the server could read the request, but the data makes no sense, and it rejects it with a 422 that says which field is wrong and why. If the body weren’t even JSON, it would answer 400. You know all three codes from lesson 3 of Phase 2, which calls the 422 by its current name, Unprocessable Content (Node still writes the old one). Now you’re the one sending them.
These are the addresses it will have:
| Request | What it does |
|---|---|
GET /products |
The list of products, in JSONJSON stands for JavaScript Object Notation.A format for writing data as text, with braces, quotes and colons: {"product":"mug","quantity":2}. People can read it, and so can almost any programming language, and it’s the most common format for the data that travels between a frontend and a backend.Go to definition. With ?max=20, only the ones that cost €20 or less |
GET /products/2 |
One product, or a 404 if it doesn’t exist |
POST /products |
Adds a product. Only someone with the admin key can do it |
GET /orders |
The orders placed |
GET /orders/1 |
One order, or a 404 if it doesn’t exist |
POST /orders |
Creates an order, after checking every piece of data |
The data is kept in the program’s memory: if you stop the server, the orders disappear. Keeping them for good in a database is Phase 5.
What you will learn
Section titled “What you will learn”By the end of this phase you’ll be able to write a small HTTP server and understand every line. You’ll know:
- What Node.jsA program that runs JavaScript outside the browser, on your computer or on a server. It uses the same engine as Chrome and adds what a web page can’t do, like reading files or listening on a port.Go to definition is and how it runs JavaScript and TypeScript outside the browser.
- How to read and write the JavaScript and TypeScript a server needs, even if you’ve never programmed before.
- How to write a server with no outside help, with what comes with Node, and see there’s no magic inside: Phase 2’s request, now in variables.
- What a FrameworkReady-made code that solves what almost every program of one kind repeats, such as a server (reading each request, deciding which route handles it and responding), and that calls your functions when the time comes. You write only what’s specific to your application. Hono, Express and Fastify are frameworks for servers.Go to definition like Hono or Express gives you, and what MiddlewareA function a server runs with the requests of the routes it’s registered on (all of them, or only some), before the code that answers them. It can answer the request itself or pass it on to the next one, and it sees the response on its way back. It’s used for what affects many requests, like writing them to the log, granting CORS permission or asking for a credential.Go to definition is.
- Never to trust what the client sends, and to check all of it.
- How to handle errors without showing your secrets, and how to write logs a machine can read.
- What the Event loopThe loop Node.js uses to handle many things at once with a single thread. It runs a piece of code to the end, checks what’s ready in its queue (a request that has arrived, a timer that has run out) and moves on to the next one. If a piece takes a long time, everything else waits.Go to definition is and why a single slow request can hold up all the others.
The lessons
Section titled “The lessons”- Node.js
- JavaScript
- TypeScript
- HTTP server
- Frameworks
- Middleware
- Validation
- Errors and logs
- Event loop
Where you will practice
Section titled “Where you will practice”Everything happens on your computer. The server listens on http://localhost:3000: localhostA name that always means “this same computer.” When you open localhost:8080, both the client and the server are on your machine.Go to definition because the client and the server are on the same machine, and 3000 because it’s the PortA number, from 0 to 65535, that says which program on a computer a connection is for. The computer has an address; each listening program has its port.Go to definition Node servers usually use while you’re writing them. You’ll call it with curl, as in Phase 2, and with the browser.
You need three things:
| What | What for |
|---|---|
| Your TerminalAn application where you give the computer instructions by typing text instead of clicking. Almost every server is managed this way.Go to definition | Starting the server, watching it write and calling it with curl |
| Node.js, installed with nvm | Running your code |
| A code editor, VS Code | Writing the project’s files and seeing mistakes before you run them |
- On Windows, everything happens in WSL, as it has since Phase 0. Node is installed inside Ubuntu, not on Windows.
- You don’t need the practice server: Phase 1’s virtual machine rests until Phase 8, where you’ll put this very API on it.
The lessons’ outputs were captured with Node 26. Your times, your dates and some numbers will be different.
Before you start: Node.js with nvm
Section titled “Before you start: Node.js with nvm”Node.js is the program that runs JavaScript outside the browser; lesson 1 tells you what it is on the inside. Here you just install it, and you do it with nvm (Node Version Manager): a program that installs Node and lets you switch versions with one command.
Why not the installer from Node’s website? For two reasons:
- Each project asks for its own version. This course uses Node 26, the long-term support (LTS) version since October 28, 2026. A project at work may ask for another one, and with nvm you switch in a second.
- It doesn’t touch the system. nvm installs everything in your home folder, without
sudo.
nvm works the same on macOS, on Linux and on WSL. If you already have Node installed some other way, that’s fine: nvm puts itself first in your PATH, the list of folders where the shell looks for programs (lesson 7 of Phase 1).
1. Install nvm
Section titled “1. Install nvm”nvm is installed with a ScriptA text file with commands that the shell runs one after another, as if you typed them. It’s for repeating a task the same way every time.Go to definition that adds a few lines to the file your shell reads when it starts: ~/.zshrc on the Mac and ~/.bashrc on Linux and WSL. On a Mac, if that file doesn’t exist, nvm doesn’t know where to write. Create it first, just in case (if it already exists, nothing happens to it):
On the Mac only
touch ~/.zshrctouch creates an empty file if it doesn’t exist, and if it does, leaves it as it was. It doesn’t write anything. On Linux and WSL you don’t need it: ~/.bashrc is there from the start.
Now, the installation. It’s the command nvm itself gives on its page, with version 0.40.8:
Install nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.8/install.sh | bashWhat you will see:
% Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed100 17883 100 17883 0 0 367k 0 --:--:-- --:--:-- --:--:-- 371k=> Downloading nvm from git to '/home/ana/.nvm'=> Cloning into '/home/ana/.nvm'...* (HEAD detached at FETCH_HEAD)master=> Compressing and cleaning up git repository
=> Appending nvm source string to /home/ana/.bashrc=> Appending bash_completion source string to /home/ana/.bashrc=> Close and reopen your terminal to start using nvm or run the following to use it now:
export NVM_DIR="$HOME/.nvm"[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completionWord by word:
curl -o-downloads the script and, instead of saving it to a file, writes it to the output (the-in-o-means “the screen”).|passes that output to the next command, as in lesson 3 of Phase 1.bashruns what it receives: the install script.
The output is from Ubuntu; in yours, the first line will have other speeds, and you can ignore the Git lines (HEAD detached, master). What matters are the two that start with Appending: nvm has added its lines to your ~/.bashrc, or to your ~/.zshrc on the Mac, with /Users/ana instead of /home/ana.
If you get Profile not found, nvm didn’t find that file: run the touch from before and repeat the command.
2. Open a new terminal and check nvm
Section titled “2. Open a new terminal and check nvm”nvm is loaded from ~/.zshrc or ~/.bashrc, and the shell only reads that file when it starts. So close the terminal and open another one. Then:
Is nvm there?
command -v nvmWhat you will see:
nvmcommand -v says whether the shell knows a command. If it answers nvm, it’s ready.
If it prints nothing, the shell hasn’t loaded nvm: check that you opened a new terminal. If it still fails, look at the end of your ~/.zshrc (or ~/.bashrc) with tail (lesson 2 of Phase 1): it must have the three NVM_DIR lines that showed up during the installation.
3. Install Node 26
Section titled “3. Install Node 26”On Linux and WSL, first install libatomic1, a piece Node 26 needs and that WSL’s Ubuntu doesn’t include: without it, nvm install seems to go well, but node won’t start. You install it with apt (lesson 6 of Phase 1): first the catalog, then the package. On the Mac you don’t need it.
On Linux and WSL only
sudo apt updatesudo apt install -y libatomic1What you will see:
…The following NEW packages will be installed:libatomic1…Setting up libatomic1:arm64 (14.2.0-4ubuntu2~24.04.1) ...We trimmed the output (…). What matters is Setting up libatomic1: it’s done. On most PCs you’ll see amd64 instead of arm64. If you already had it, apt says libatomic1 is already the newest version.
Install Node 26
nvm install 26What you will see:
Downloading and installing node v26.11.1...Downloading https://nodejs.org/dist/v26.11.1/node-v26.11.1-linux-arm64.tar.gz...######################################################################## 100.0%Computing checksum with sha256sumChecksums matched!Now using node v26.11.1 (npm v11.20.0)Creating default alias: default -> 26 (-> v26.11.1 *)nvm install 26 looks for the most recent version of Node 26 and installs it. Line by line:
Downloading: it fetches Node from its official website,nodejs.org. The end of the name says which system and which processor it’s for: on a Mac you’ll seedarwininstead oflinux, and on most PCs,x64instead ofarm64.Checksums matched!: nvm has checked that the file is identical to the published one, with a HashA short, fixed-size summary calculated from some data, like a fingerprint. The same data always gives the same hash, and the smallest change gives a completely different one. Git calls each commit by its hash.Go to definition, the fingerprint Git uses to name each commit (lesson 10 of Phase 1). If the file had arrived broken or changed, it would stop here. On the Mac, this line may name a different tool (shasum).Now using node v26.11.1 (npm v11.20.0): you have it, and with it npmThe package manager of Node.js, which comes installed with it. It’s both a command, which downloads packages into your project, and a public catalog on the internet where anyone can publish them. Although it’s often read as “Node Package Manager,” officially it isn’t an acronym.Go to definition, which comes included. You’ll use it from lesson 1 on.default -> 26: it’s the version every new terminal will have.
Your version numbers may be higher: Node publishes fixes every few weeks, and everything in this course works with any Node 26.
4. Check the versions
Section titled “4. Check the versions”Node and npm
node --versionnpm --versionWhat you will see:
v26.11.111.20.0Both commands print their version and finish. The first one must start with v26.
If you get another one, for example v22, that terminal is still using a Node you already had: open a new one, or type nvm use 26.
On Linux or WSL, if you get error while loading shared libraries: libatomic.so.1, you’re missing libatomic1: install it as in step 3 and try again.
Before you start: the editor
Section titled “Before you start: the editor”Until now you’ve edited files with nano, inside the terminal. A project has many files, and a code editor helps you with them: it colors each part of the code, shows you all the folders at once and, above all, underlines mistakes while you type. In lesson 3 you’ll see why that’s worth so much.
The course uses VS Code (Visual Studio Code), from Microsoft: it’s free, it works on all three systems and it’s the most widely used. If you already have another editor you like, stick with it: the lessons only use VS Code for what the terminal doesn’t show.
- macOS and Linux: download it from code.visualstudio.com and install it like any other application.
- Windows: install it on Windows, not inside Ubuntu, and add its “WSL” extension (in the Extensions panel). With it, VS Code on Windows opens and edits the folders in your Ubuntu.
- Language: the lessons name the menus in English, as VS Code comes. If your system is in another language, VS Code will offer you its language pack.
The easiest way is to open the editor from the terminal, in the folder you’re in, with code . (the dot is “this folder”, as in Phase 1). On Linux and WSL it works from the start. On the Mac, you first have to teach it to the shell: open VS Code, press Cmd + Shift + P, type shell command and choose Shell Command: Install ‘code’ command in PATH.
Before you start: the project folder
Section titled “Before you start: the project folder”Each phase has its folder in ~/backend-course, the one from Phase 1. The shop’s API will live in shop-api, inside this phase’s folder:
Your project folder
mkdir -p ~/backend-course/phase-3/shop-apicd ~/backend-course/phase-3/shop-apipwdWhat you will see:
/Users/ana/backend-course/phase-3/shop-apiThey’re the three commands from the Phase 1 introduction: mkdir -p creates any missing folders, cd goes into the last one and pwd says where you are. On Linux and WSL the path starts with /home/ana instead of /Users/ana, with your username.
Open it in the editor with code .. On the left you’ll see the folder, empty: there’s nothing in it yet.
Try it: your first program
Section titled “Try it: your first program”The goal: get Node to run a program you wrote and tell you which version it ran it with. It’s the project’s first file: a comment and two commands.
// Your first Node.js program: it writes two lines in the terminal.console.log('Hello from Node.js');console.log(`You're using Node.js ${process.version}`);Piece by piece:
- The line that starts with
//is a comment: a note for whoever reads the code. Node skips it, just as nginx skipped the lines with#. console.log(…)writes in the terminal what’s between the parentheses, and goes to a new line.'Hello from Node.js'is a piece of text. The quotes mark where it starts and where it ends: they aren’t written on the screen.- The third line uses backticks (
`), which let you put a value inside the text with${…}. process.versionis the version of the Node that’s running the program.processis the ProcessA running program. When you start a server, the operating system creates a process that stays alive waiting for requests.Go to definition from lesson 5 of Phase 1, seen from the inside.
Lesson 2 goes back over each of these pieces calmly. To create the file, in VS Code choose File › New File…, name it hello.js and type the three lines inside. Type them yourself instead of copying them: that’s how you get used to the punctuation. Save with Cmd + S (Ctrl + S on Windows and Linux).
Run it
node hello.jsWhat you will see:
Hello from Node.jsYou're using Node.js v26.11.1node followed by a file name reads the file and runs what’s inside, line by line. When it gets to the end, it finishes and gives you back the prompt.
Look at the second line: where the code said ${process.version}, your version came out. You wrote the text; Node put that number there when it ran it.
If you get Error: Cannot find module '…/hello.js', Node can’t find the file in the folder you’re in. Look at the path in the error: check with pwd that you’re in shop-api, and with ls that the file is called hello.js, with no .txt at the end. If you get SyntaxError, a quote or a parenthesis is missing: compare your file with the one above, character by character.
You now have a program that works. In lesson 1, this file becomes the first one of a real Node project.
If you get stuck: each lesson’s code
Section titled “If you get stuck: each lesson’s code”One missing comma is enough to stop a program from starting, and sometimes it’s hard to find. That’s why each lesson’s code can be downloaded, just as it is at the end of the lesson, so you can compare it with yours.
Each lesson has its own, with its number in front: 01-node, 02-javascript, 03-typescript… up to 09-event-loop. You download them like this, from the phase’s folder, so they don’t get mixed up with your project. For example, lesson 1’s:
Download lesson 1's folder
cd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/01-node.tar.gztar -xzf 01-node.tar.gzWhat you will see:
% Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed100 1233 100 1233 0 0 344k 0 --:--:-- --:--:-- --:--:-- 401kcurl -Osaves what it downloads to a file with the same name,01-node.tar.gz, as in the Phase 2 introduction. The repeated number is its size in bytes: yours will be similar, but it may change when we update the code, and the speeds will be different.- A
.tar.gzis a folder packed into a single file (tar) and compressed (gz), like a.zip. tar -xzfunpacks it:xfor extract,zbecause it’s compressed andffor file. It prints nothing if all goes well.
If tar says Unrecognized archive format (on the Mac) or not in gzip format (on Linux), you didn’t download the folder but an error page: check the address and download it again.
Now, next to your shop-api, you have a 01-node folder with the project as it is at the end of lesson 1:
What's inside?
ls -A 01-nodeWhat you will see:
.gitignore.npmrc.nvmrchello.jspackage-lock.jsonpackage.jsonproducts.jsonread-products.jstestls -A also shows hidden files, the ones that start with a dot (lesson 1 of Phase 1); in your terminal they’ll come out in columns. There’s your hello.js. You’ll meet the others in lesson 1. One is useful right away: .nvmrc says which Node version the project asks for, and if you type nvm use inside the folder, nvm switches to that version.
To try a downloaded folder, go into it and install what the project needs:
Set it up
cd 01-nodenpm installWhat you will see:
up to date, audited 1 package in 182ms
found 0 vulnerabilitiesnpm install downloads the packages the project uses: code written by other people, which you’ll see in lesson 1. This one doesn’t use any yet, and that’s why it says up to date. From lesson 3 on, each folder brings its own, and this command downloads them. Your time will be different.
To compare, open both files in VS Code, yours and the downloaded one, side by side. When you’re done, go back to your project: cd ../shop-api.
Use it to compare, not to skip the writing. You learn code by writing it, getting it wrong and reading the error. The downloaded folder is there for when you’ve been stuck for a while.
You have everything now: Node 26, an editor and your first program running. Start with lesson 1, “Node.js”: you’ll see what that program that just ran your code is, and you’ll turn your folder into a project.