15 min read
Hono vs Express vs Fastify: Node.js frameworks
In one sentence: A framework is code already written that does what every server repeats: deciding which function handles each request, reading its data and answering in JSON. Express is the most used, Fastify was born to be fast, and Hono, the one in this course, uses the same Request and Response as fetch.
What you will learn
- Explain what a framework adds to a server built with node:http, and what doesn't change.
- Move the shop's API to Hono, with route parameters and query strings.
- Answer 405 with Allow to a method a route doesn't accept, because the framework doesn't do it on its own.
- Compare the same route in Express and in Fastify, and know what to look at to choose.
Before you start, read: 04-http-server.md
The problem
Section titled “The problem”In lesson 4 you wrote the shop’s API with node:http alone. It works, but look at how it finds out which product is being asked for: pathname.match(/^\/products\/(\d+)$/). That’s a regular expression, a text pattern you have to read with a magnifying glass, and all it does is pull the 2 out of /products/2. On top of that, every route repeats its own if (req.method !== 'GET').
Now Ana wants to filter by price: /products?max=25, “the products that cost €25 or less.” Later she’ll want to create products. Every new idea is another if, another regular expression and another place to make a mistake.
And every server needs the same things: sorting out the requests, reading the data in the URL and in the body, and answering in JSON. That’s what frameworks are for: code that already solves that part, so you only write yours.
The analogy
Section titled “The analogy”The analogy
Think of the front desk of an office building. Visitors don’t go from office to office: they say what they’ve come for, and the receptionist checks the directory and tells them where to go. “An invoice? Accounting, second floor.” If they bring a case number, the receptionist writes it on the slip they hand over, and the office doesn’t have to ask for it again.
You write the directory, and the receptionist applies it to every visit. In lesson 4 you did both jobs. The visitor is the request; the directory, your list of routes; each office, the function that answers; and the case number, the 2 in /products/2.
Where the analogy breaks down
- A receptionist understands what you want even if you say it your own way. The framework only compares patterns:
/product/2, without the “s”, matches nothing and gets a404. - A receptionist would tell you “we don’t do that here; only inquiries.” Hono, Express and Fastify answer
404to a wrong method: you write the405yourself. - The building hired the receptionist. Other people wrote the framework: your server depends on their code, their versions and their bugs.
How it really works
Section titled “How it really works”What a framework does for you
Section titled “What a framework does for you”This is the same API, in lesson 4 and in this one:
| What’s needed | In lesson 4, with node:http |
With Hono |
|---|---|---|
| Choosing which code handles the request | One if per route, and a regular expression |
app.get('/products/:id', …) |
Reading the 2 in /products/2 |
What the regular expression captured, route[1] |
c.req.param('id') |
Reading the 25 in ?max=25 |
It didn’t: you’d have to read the URL by hand | c.req.query('max') |
| Reading the body of an order | readBody, chunk by chunk, and JSON.parse |
await c.req.json() |
| Answering in JSON | writeHead, JSON.stringify and end |
c.json(data) |
That’s 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 is: code already written that solves what every server repeats, and that calls your functions when a request arrives. The difference from any other Package (of code)Ready-to-use code that someone publishes with a name and a version number, so others can install it in their projects instead of writing it. In Node.js, packages are installed with npm and kept in the node_modules folder.Go to definition, like the ones in lesson 1, is who calls whom: you call a package; a framework calls you.
What doesn’t change is HTTP. The request still brings its method, its headers and its body, and a 404 is still a 404, as in Phase 2. The framework only saves you code.
Why Hono in this course
Section titled “Why Hono in this course”Of the three best-known frameworks for Node.js, Express, Fastify and Hono, this course uses Hono for three reasons:
- It speaks like
fetch. It uses theRequestandResponseObjectA value that groups several pieces of data, each with its own name, such as { name: "Mug", price: 8.5 }. Each piece is read with a period and its name, such as product.price.Go to definition offetch, the function the browser makes requests with; you used it in the console in lesson 6 of Phase 2. What you learn here works there, and the other way around. - It runs in many places. The same code runs on Node.js and on Cloudflare Workers, the servers this site is published on, among others.
- It’s small and written in 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. It’s a single package, with no dependencies.
Installing Hono with the exact version
Section titled “Installing Hono with the exact version”In your project folder, ~/backend-course/phase-3/shop-api:
Install Hono and its adapter for Node.js
npm install hono@4.13.18 @hono/node-server@2.1.8What you will see:
added 2 packages, and audited 7 packages in 3s
found 0 vulnerabilitieshono is the framework, and @hono/node-server, the adapter that connects it to node:http; the @hono/ says it’s published by Hono’s authors. The @ and the number pin the exact version, as in lesson 1. added 2 packages: neither of them brings dependencies.
The outputs are from Node 26.11 and npm 11.20, on Linux; on a Mac they come out the same, with other times and dates. If you get npm error code ETARGET, that version doesn’t exist or is less than seven days old: check the number.
The startup: server.ts
Section titled “The startup: server.ts”Replace src/server.ts with this:
// Starts the API with Hono's server for Node: it listens on port 3000, only on this computer.import { serve } from '@hono/node-server';import { app } from './app.ts';
serve({ fetch: app.fetch, port: 3000, hostname: '127.0.0.1' }, (info) => { console.log(`The shop is listening on http://localhost:${info.port}`);});- The two
importlines bring inserve, the function that starts the server, and your API, which you’ll write now inapp.ts. serve({ … }, (info) => …)creates anode:httpserver underneath, the one from lesson 4.fetch: app.fetchtells it whom to hand each request to: your app.port: 3000, hostname: '127.0.0.1': port 3000, and only on this computer, as before.- The function at the end runs once the server is listening;
info.portis its port.
Request and Response: the fetch objects
Section titled “Request and Response: the fetch objects”app.fetch is a function that receives a Request and returns a Response. A Request carries the method, the URL, the headers and the body; a Response, the code, the headers and the body. It’s the HTTP message from Phase 2, in two objects.
node:http doesn’t use those objects: it gives you req and res, as you saw in lesson 4. The adapter translates in both directions:
- curlGET /products/2
the bytes arrive over TCP
- node:httpreads them into req
@hono/node-server translates it
- A Requestlike the ones in fetch
app.fetch looks for the route
- Your functionreturns a Response
the adapter writes it into res
- curlgets the response
On Cloudflare Workers you don’t need the adapter: the platform hands app.fetch a Request directly. That’s why app.ts works the same there, and the only part specific to Node.js is server.ts.
The app and its routes
Section titled “The app and its routes”Now, src/app.ts. It starts like this:
import { Hono } from 'hono';import { createOrder, findOrder, findProduct, orders, products } from './data.ts';
export const app = new Hono();import { Hono } from 'hono'brings in the framework.- The second line brings in the products, the orders and their functions from
data.ts, which hasn’t changed since lesson 4. new Hono()creates the app, andexportletsserver.tsand the tests use it.
The routes go below. A Route (on a server)Each combination of HTTP method and URL path that a server knows how to handle, such as GET /products, together with the function that responds to those requests. A request that matches no route gets a 404.Go to definition is a method, a path and the function that answers:
app.get('/', (c) => c.text("Ana and Luis's shop. Try /products and /orders.\n"));
// ?max=25: only the products that cost that much at most.app.get('/products', (c) => { const max = c.req.query('max'); if (max === undefined) return c.json(products); return c.json(products.filter((product) => product.price <= Number(max)));});
// :id is a route parameter: /products/2 leaves it in c.req.param('id').app.get('/products/:id', (c) => { const product = findProduct(Number(c.req.param('id'))); if (!product) return c.json({ error: 'No such product' }, 404); return c.json(product);});
app.get('/orders', (c) => c.json(orders));
app.get('/orders/:id', (c) => { const order = findOrder(Number(c.req.param('id'))); if (!order) return c.json({ error: 'No such order' }, 404); return c.json(order);});Piece by piece:
app.get('/', …)adds to Hono’s list a route forGETrequests to/.(c) => …is an arrow function (lesson 2) that receivesc, the context: the request is inc.req, andchas the methods to answer.c.text('…')answers200with text.c.req.query('max')reads themaxin the Query stringThe part of a URL that comes after “?”: data in name=value pairs separated by “&”, such as q=mug&sort=price. It travels to the server attached to the path, and it’s used to search, filter or choose a page of results.Go to definition. If the URL doesn’t bring it, it givesundefined.c.json(products)answers200, withContent-Type: application/jsonand the list in JSON.products.filter(…)keeps the ones that costmaxor less.Number(max)is needed because everything that comes in a URL is text.'/products/:id': the colon turnsidinto a Route parameterA variable piece of a route, marked with a colon: in /products/:id, the :id. The route accepts any value there (/products/2, /products/7) and hands it to your code, always as text. It says which resource you’re asking for; to filter or search a list, you use the query string.Go to definition. The route matches/products/2and/products/7, andc.req.param('id')gives'2', also as text.c.json({ error: … }, 404): the second argument is the Status codeA three-digit number at the start of every HTTP response that sums up what happened. 200 means “all good,” 404 “that doesn’t exist” and 400 “your request is malformed.”Go to definition. Without it, it’s200.- The two
/ordersroutes repeat the idea: the whole list, and one order by its number, or a404if it doesn’t exist.
A rule for choosing: the route parameter says which resource you’re asking for (product 2); the query string filters or searches a list (the ones at €25 or less).
The body of an order
Section titled “The body of an order”app.post('/orders', async (c) => { let data: { productId: number; quantity: number }; try { data = await c.req.json(); } catch { return c.json({ error: 'The body is not valid JSON' }, 400); } if (!findProduct(data.productId)) { return c.json({ error: 'No such product' }, 422); } const order = createOrder(data.productId, data.quantity); return c.json(order, 201, { Location: `/orders/${order.id}` });});app.post('/orders', …): the same path asapp.get('/orders'), with another method, is another route.await c.req.json()reads the whole body and converts it from JSON: Hono puts together the chunks thatreadBodyused to put together. Because of theawait, the function is markedasync.tryandcatch: if the body isn’t JSON,c.req.json()fails and thecatchanswers400, as in lesson 4.let data: { productId: number; quantity: number }promises TypeScript a shape that nobody checks:c.req.json()returns whatever arrived. You’ll fix that in lesson 7.if (!findProduct(…)): the JSON was read fine, but it asks for a product that doesn’t exist. That’s a422, not a400: the request is understood, and what it asks for makes no sense (the status codes lesson).c.json(order, 201, { Location: … }): the third argument is the headers. A201withLocation, the address of the new order, which theGET /orders/:idroute handles.
A wrong method: Hono answers 404
Section titled “A wrong method: Hono answers 404”With the routes you have so far, this is what Hono answers to a DELETE /products:
A method that no route accepts
curl -i -X DELETE localhost:3000/productsWhat you will see:
HTTP/1.1 404 Not FoundContent-Type: text/plain; charset=UTF-8Date: Tue, 13 Oct 2026 11:30:07 GMTConnection: keep-aliveKeep-Alive: timeout=5Content-Length: 13
404 Not FoundA 404 in text. Hono looks for a route for DELETE /products, doesn’t find one and answers the same as to a route that doesn’t exist.
But /products exists; what it doesn’t accept is that method. The methods lesson made it clear: that’s a 405, with the Allow header. Express and Fastify also answer 404, so in all three you write it yourself:
// Hono answers 404 to a method that a route doesn't have. To answer 405 with Allow, as in// lesson 4, you add a route for the other methods, after the rest.app.all('/products', (c) => c.json({ error: 'Method not allowed' }, 405, { Allow: 'GET' }));app.all('/products/:id', (c) => c.json({ error: 'Method not allowed' }, 405, { Allow: 'GET' }));app.all('/orders', (c) => c.json({ error: 'Method not allowed' }, 405, { Allow: 'GET, POST' }));app.all('/orders/:id', (c) => c.json({ error: 'Method not allowed' }, 405, { Allow: 'GET' }));app.allcreates a route for any method, one for each path in the API.- They go after the rest. Hono tries the routes in the order you wrote them, so
app.allonly gets what nobody has handled before. - The third argument sets the
Allowheader with the methods that are valid.
The same route in Express and in Fastify
Section titled “The same route in Express and in Fastify”This is how GET /products is written with the other two. They go in a separate folder, compare/, because they’re not part of the API:
// The same route with Express, to compare. Start it with: node compare/express.tsimport express from 'express';import { products } from '../src/data.ts';
export const app = express();
app.get('/products', (req, res) => { res.json(products);});
if (import.meta.main) { app.listen(3001, '127.0.0.1', () => console.log('Express is listening on http://localhost:3001'));}// The same route with Fastify, to compare. Start it with: node compare/fastify.tsimport Fastify from 'fastify';import { products } from '../src/data.ts';
export const app = Fastify();
app.get('/products', async () => products);
if (import.meta.main) { await app.listen({ port: 3002, host: '127.0.0.1' }); console.log('Fastify is listening on http://localhost:3002');}- Express gives you
reqandres: the samenode:httpobjects as in lesson 4, with more methods.res.json(products)sends the list in JSON. - Fastify doesn’t ask you to answer: the function returns the data and Fastify turns it into JSON.
import.meta.mainistrueonly when you run that file withnode. If a test imports it, it doesn’t open any port.- Ports 3001 and 3002 let them run at the same time as Hono, on 3000.
How to choose
Section titled “How to choose”| Express | Fastify | Hono | |
|---|---|---|---|
| Weekly downloads on npm (October 13, 2026) | 145 million | 15 million | 74 million |
| Since | 2010 | 2016 | 2021 |
| Packages it installs | 68 | 48 | 1 |
| Your functions receive | req and res from node:http |
The request, and they return the data | c, with a Request inside |
| TypeScript | Separate types, from the community (@types/express) |
Types included | Written in TypeScript |
| Designed for | Node.js | Node.js | Node.js, Cloudflare Workers, Deno, Bun… |
We counted the packages by installing each one in an empty folder. Express is what you’ll find most in job listings and tutorials. Fastify was born to be fast, and it validates data with SchemaThe description of what some data must look like: which fields it has, whether each one is a number or text, and which values are accepted. A program compares the incoming data with it and says whether it matches or what’s wrong.Go to definition, a description of its shape. Hono is the newest.
What you learn with one carries over to the others: routes, parameters, status codes and the 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 of lesson 6. Switching frameworks is learning other names for the same ideas.
Try it
Section titled “Try it”The goal: check that your API with Hono filters by price, reads the id from the route and answers 405 and 422 when it should, and see what Express adds without you asking.
First, the tests. The ones from lesson 4 use createShopServer, which your new app.ts no longer has: npm test would fail with does not provide an export named 'createShopServer'. The new ones come in this lesson’s folder. Download it into the phase folder, as in the introduction, and swap one test for the other:
cd ~/backend-course/phase-3curl -O https://backenddesdecero.com/practicas/shop-api/05-framework.tar.gztar -xzf 05-framework.tar.gzcd shop-apirm test/server.test.tscp ../05-framework/test/app.test.ts test/rm deletes the old test and cp copies the new one. The other one, compare.test.ts, needs Express and Fastify: you’ll copy it at the end. If you get stuck, compare your code with the one in 05-framework.
1. Start the API
npm startWhat you will see:
> shop-api@1.0.0 start> node src/server.ts
The shop is listening on http://localhost:3000Open another terminal for the rest. If you get EADDRINUSE, the server from lesson 4 is still running: stop it with Ctrl + C in its terminal.
2. The products at €25 or less
curl -i "localhost:3000/products?max=25"What you will see:
HTTP/1.1 200 OKContent-Type: application/jsonDate: Tue, 13 Oct 2026 11:30:10 GMTConnection: keep-aliveKeep-Alive: timeout=5Content-Length: 72
[{"id":1,"name":"T-shirt","price":20},{"id":2,"name":"Mug","price":8.5}]Two products: the hoodie, at €35, has been left out. The quotes are needed in zsh, the Mac’s shell (see “Common mistakes”).
3. A product by its id
curl -i localhost:3000/products/2What you will see:
HTTP/1.1 200 OKContent-Type: application/jsonDate: Tue, 13 Oct 2026 11:30:10 GMTConnection: keep-aliveKeep-Alive: timeout=5Content-Length: 33
{"id":2,"name":"Mug","price":8.5}The mug: Hono has pulled the 2 out of the route. Try /products/99: you get {"error":"No such product"}, with a 404.
4. A wrong method, done right this time
curl -i -X DELETE localhost:3000/productsWhat you will see:
HTTP/1.1 405 Method Not Allowedallow: GETcontent-type: application/jsonContent-Length: 30Date: Tue, 13 Oct 2026 11:30:10 GMTConnection: keep-aliveKeep-Alive: timeout=5
{"error":"Method not allowed"}The 405 with allow: GET. If you get a 404, check that you wrote the app.all routes after the rest. The lowercase doesn’t matter: when you pass it headers, Hono writes the names that way, and they’re case-insensitive.
5. An order for a product that doesn't exist
curl -i --json '{"productId":99,"quantity":1}' localhost:3000/ordersWhat you will see:
HTTP/1.1 422 Unprocessable EntityContent-Type: application/jsonDate: Tue, 13 Oct 2026 11:30:10 GMTConnection: keep-aliveKeep-Alive: timeout=5Content-Length: 27
{"error":"No such product"}The body is JSON, so it’s not a 400; but product 99 doesn’t exist: 422. Change the 99 to a 2 and you get a 201 with location: /orders/1, which curl localhost:3000/orders/1 gives back to you.
Now, Express. Stop the API with Ctrl + C, like any process, and create the compare/ folder with the two files from before. Install the two frameworks and Express’s types, which come separately:
6. Install Express and Fastify
npm install express@5.3.0 fastify@5.12.7What you will see:
added 113 packages, and audited 120 packages in 4s
49 packages are looking for fundingrun `npm fund` for details
found 0 vulnerabilitiesHono installed 2 packages; these two, 113, with their dependencies. looking for funding tells you some of them accept donations.
7. And Express's types
npm install --save-dev @types/express@5.0.6What you will see:
added 9 packages, and audited 129 packages in 711ms
49 packages are looking for fundingrun `npm fund` for details
found 0 vulnerabilities--save-dev lists them under devDependencies, as in lesson 3: they’re only needed to check the types.
8. Start the Express version
node compare/express.tsWhat you will see:
Express is listening on http://localhost:30019. The same request, to port 3001
curl -i localhost:3001/productsWhat you will see:
HTTP/1.1 200 OKX-Powered-By: ExpressContent-Type: application/json; charset=utf-8Content-Length: 108ETag: W/"6c-fiNvh0kfdaV0FLHGFhyr0N4m5ow"Date: Tue, 13 Oct 2026 11:30:32 GMTConnection: keep-aliveKeep-Alive: timeout=5
[{"id":1,"name":"T-shirt","price":20},{"id":2,"name":"Mug","price":8.5},{"id":3,"name":"Hoodie","price":35}]The same JSON, 108 bytes, and two headers you didn’t write:
X-Powered-By: Expresstells anyone what your server is built with, a useful clue for someone looking for known bugs. You remove it withapp.disable('x-powered-by').ETagis the fingerprint of the response, the one from the caching lesson. Express calculates it on its own.
Challenge: what does Express answer to curl -i -X DELETE localhost:3001/products? Does it do what Phase 2 asks for?Show answer
It doesn’t either. It answers a 404, and in HTML:
HTTP/1.1 404 Not FoundX-Powered-By: ExpressContent-Security-Policy: default-src 'none'X-Content-Type-Options: nosniffContent-Type: text/html; charset=utf-8Content-Length: 150Date: Tue, 13 Oct 2026 11:30:32 GMTConnection: keep-aliveKeep-Alive: timeout=5
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Error</title></head><body><pre>Cannot DELETE /products</pre></body></html>No 405 and no Allow. The fix is the same as in Hono: an app.all('/products', …) after the GET route, answering 405 with its header.
When you’re done, stop Express with Ctrl + C. Finally, copy the missing test and run them all:
10. Run the tests
cp ../05-framework/test/compare.test.ts test/npm testWhat you will see:
> shop-api@1.0.0 test> node --test
✔ GET / answers with text (25.83497ms)✔ GET /products returns all three; with ?max=25, two (1.824093ms)✔ GET /products/2 returns the mug; /products/99, a 404 (0.615943ms)✔ POST /orders creates an order: 201 with Location (0.986454ms)✔ the Location address exists; an order that does not exist, 404 (0.90676ms)✔ POST /orders with a body that is not JSON: 400 (0.468717ms)✔ POST /orders with a product that does not exist: 422 (0.810768ms)✔ a method the route does not accept: 405 with Allow (0.483301ms)✔ a route that does not exist: 404 (0.2288ms)✔ Express returns the same products (31.239548ms)✔ Fastify returns the same products (10.139514ms)ℹ tests 11ℹ suites 0ℹ pass 11ℹ fail 0ℹ cancelled 0ℹ skipped 0ℹ todo 0ℹ duration_ms 267.135671Eleven tests and fail 0: nine for your API with Hono and two that ask Express and Fastify for /products. Your times will be different. If one fails, it comes out with ✖ and what it expected next to what it got: compare that piece with the one in the download.
You have already seen it
Section titled “You have already seen it”- Route parameters in the addresses you visit. In
github.com/user/repositorytwo pieces change depending on what you’re looking at, and inyoutube.com/watch?v=…the video goes in the query string. X-Powered-Byin DevTools. In the Network tab of some websites you’ll seeX-Powered-By: ExpressorX-Powered-By: Next.jsamong the response headers: it’s the header you just saw on 3001.fetchin the console. Theawait fetch(…)from the CORS lesson returns aResponse, like your Hono routes.
Common mistakes
Section titled “Common mistakes”- A URL with
?and no quotes in zsh.curl localhost:3000/products?max=25answerszsh: no matches found: localhost:3000/products?max=25: to zsh,?is a file name wildcard. Put the URL in quotes. - Using a parameter as if it were a number.
c.req.param('id')gives'2', text, and'2' === 2is false: the search never finds anything. If you pass the text tofindProduct,npm run checkwarns you:error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. app.allbefore the other routes. Even theGETrequests get the405.- Thinking the framework checks the data.
?max=cheapanswers200with[], without an error:Number('cheap')isn’t a number, and no price passes the filter. You’ll fix that in lesson 7. - Copying a tutorial for another version. Express 5 no longer accepts
app.get('*', …): it fails on startup withMissing parameter name at index 1: *. The wildcard now has a name,'/*rest'. Always check the tutorial’s version.
Summary
Section titled “Summary”- A framework does what every server repeats: choosing the route, reading its parameters, the query string and the body, and answering in JSON. You write what’s specific to your shop.
- A route is a method, a path and the function that answers.
:idmarks a parameter, which always arrives as text. - Hono works with the
RequestandResponseoffetch;@hono/node-servertranslates them from and tonode:http. - HTTP doesn’t change: you write the
405withAllowyourself, in Hono, in Express and in Fastify. - Express is the most used, Fastify was born to be fast and Hono is the smallest. The ideas work in all three.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Hono on Node.js: how to start it with
@hono/node-server. - Routing in Hono: parameters, wildcards and the order they’re tried in.
- Routing in Express: Express’s guide.
- Migrating to Express 5: what changed since Express 4, the wildcard included.
- Fastify: Getting Started.
- Response (MDN): the object that
fetchand your Hono routes return.