16 min read
Node.js middleware: what it is and how it works
In one sentence: A middleware is a function requests go through before they reach their route, on the routes where you register it: it can answer by itself or pass the request on to the next layer, and it sees the response on its way back. It lets you write once what affects many routes, like logging each request, giving CORS permission or asking for a token.
What you will learn
- Explain the lifecycle of a request in a server with middleware, on the way in and on the way back.
- Write a middleware that measures how long each request takes and another that answers 401 if the token is missing.
- Add CORS to the API with Hono's middleware and check it with curl, preflight request included.
- Put the middleware in order and recognize what breaks with the wrong order.
Before you start, read: 05-frameworks.md phase-2/06-cors.md
The problem
Section titled “The problem”The shop’s API from lesson 5 already answers curl. Now Ana and Luis ask it for three things:
- Luis wants to use it from the shop’s page,
https://shop.example. Hisfetchfails with the CORSCORS stands for Cross-Origin Resource Sharing.The way a server tells the browser which other origins may read its responses from a page’s code, with headers such as Access-Control-Allow-Origin. The browser enforces it, not the server.Go to definition error from lesson 6 of Phase 2. - Ana wants to know which requests arrive and how long each one takes: one line per request, like nginx’s 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.
- Both want products to be created with
POST /products, but only by Ana, with a token.
The first two affect every 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, and the third affects one that may have siblings tomorrow. You could copy the same lines at the start of each route, but there are already half a dozen, and forgetting one is enough to let a request slip through unlogged or without permission. 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 solve it with a piece you write once and put in front of all of them: middleware.
The analogy
Section titled “The analogy”The analogy
Imagine you’re going to an office in a big building. At the door, the receptionist writes down in a book the time you come in. Then the security guard asks for your card: if you don’t have it, they tell you “you can’t come in,” and you go back the way you came. If you have it, you reach the office, which is where they actually help you.
On your way out, you walk the same path in reverse: you go past the guard and the receptionist again, who writes down the time you leave. That way they know how long you were inside, and whether you left with what you came for.
Where the analogy breaks down
- On the server nobody is watching: each layer is a function that runs with each request that reaches it.
- The receptionist only watches. A middleware can also change the response on its way back, for example by adding a header, as if someone stamped the paper you carry.
- In the building, the order is decided by the architecture. On the server you decide it, with the order of the lines of code, and if you change it, what happens changes.
How it really works
Section titled “How it really works”The request goes through the layers in order
Section titled “The request goes through the layers in order”These two lines go in src/app.ts, right below export const app = new Hono();:
// Order matters: each request goes through the layers in the order they're added.app.use(requestLog);app.use(cors({ origin: 'https://shop.example' }));app.use(…) adds a layer that every request goes through, whatever its route and its method. Here there are two: requestLog, which you’ll write, and cors, which comes with Hono. They run in the order of the lines, and the routes come after.
This is what happens with a GET /products that comes from Luis’s page:
- requestLognotes the start time
- corsthe origin is allowed:
prepares Access-Control-Allow-Origin - The route GET /productsthe list, in JSON
- The route GET /products → cors200 OK
- corsadds Vary: Origin
- cors → requestLog200 OK
- requestLogwrites “GET /products 200 3 ms”
- requestLog → curl or the browser200 OK
That journey is the lifecycle of a request: it comes in, goes through each 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 in the order you added them, reaches its route’s function, and the response comes back through the same layers, in reverse order. That’s why it’s often drawn as an onion: the route in the center and each middleware a layer around it. (These aren’t the network layers of Phase 0: here everything happens inside your program.)
A middleware is a function with next
Section titled “A middleware is a function with next”This is the whole request log:
import type { MiddlewareHandler } from 'hono';
// Logs each request with its method, its path, its status code and how long it took.export const requestLog: MiddlewareHandler = async (c, next) => { const start = performance.now(); await next(); // here the request goes on to the next layer, and waits for the response to return const ms = Math.round(performance.now() - start); console.log(`${c.req.method} ${c.req.path} ${c.res.status} ${ms} ms`);};Piece by piece:
import type { MiddlewareHandler }brings in just a type from Hono, the type of a middleware function (lesson 3). It runs nothing: it’s there so the editor knows whatcandnextare.export const requestLog: MiddlewareHandler = async (c, next) => { … }is the function, with that type;exportlets you use it fromapp.ts.cis the same context as in the routes of lesson 5: with it you read the request (c.req) and the response (c.res).nextis a function that passes the request on to the next layer.performance.now()gives the milliseconds, with decimals, that the program has been running. It isn’t the clock time: it’s for subtracting two of them to know how much time went by.await next()is the key line. It passes the request inward and waits for the response to come back (theawaitfrom lesson 2). What comes before it runs on the way in; what comes after, on the way back.c.res.statusis the status code the inner layers decided on. That’s why it’s read afternext(): before it, the route hasn’t answered yet.Math.round(…)rounds the difference to whole milliseconds.console.logwrites a line in the server’s terminal with the method (c.req.method), the path (c.req.path), the code and the milliseconds.
A middleware can do three things: pass the request on (await next()), answer by itself (return a response without calling next), or do something before and after, like this one. The routes of lesson 5 were the same thing, but without next: they always answer.
CORS, a ready-made middleware
Section titled “CORS, a ready-made middleware”The second layer, app.use(cors({ origin: 'https://shop.example' })), comes with Hono (hono/cors). It does what the shop’s nginx did in Phase 2 with its add_header lines, but from the code:
- A normal request with
Origin: https://shop.example: on the way in it preparesAccess-Control-Allow-Origin, callsnext()and, on the way back, addsVary: Origin, which tells caches that the response depends on that header. - An origin that isn’t on the list: it doesn’t add the permission, but it lets the request through, and the route answers. The one that hides the response is the browser, as you saw in Phase 2.
- A Preflight requestThe check the browser sends to another origin before a request that isn’t simple (for example, one that deletes data or carries custom headers), to ask the server whether it accepts it. It uses the OPTIONS method, and if the server doesn’t allow it, the real request is never sent.Go to definition (
OPTIONS): it answers by itself, with a204and the permissions, without callingnext(). The route never even finds out.
Unless you tell it otherwise, Hono gives permission for seven methods (GET,HEAD,PUT,POST,DELETE,PATCH,QUERY), even though the API only handles some of them. QUERY is the newest: a search that carries its conditions in the body. That’s fine: the CORS permission doesn’t create routes, and a PUT would still get its 405. If you want to fine-tune it, the allowMethods option takes the exact list.
A guard that answers 401
Section titled “A guard that answers 401”To create products you need a token, the secret string that travels in the Authorization: Bearer … header (lesson 4 of Phase 2). This middleware checks it:
import type { MiddlewareHandler } from 'hono';import { ADMIN_TOKEN } from '../config.ts';
// If the request doesn't bring the token, it answers 401 and doesn't let it through.export const adminOnly: MiddlewareHandler = async (c, next) => { if (c.req.header('Authorization') !== `Bearer ${ADMIN_TOKEN}`) { return c.json({ error: 'A valid token is required' }, 401, { 'WWW-Authenticate': 'Bearer', }); } await next();};c.req.header('Authorization')reads that header from the request; if it isn’t there, it givesundefined.!==means “not equal to.” It’s compared withBearerfollowed by the token, using a template string (lesson 2).return c.json(…, 401, { … })answers and, withreturn, ends the function.next()never gets to run, and so neither does the route.'WWW-Authenticate': 'Bearer'is the header the standard requires in every401: it says how to identify yourself, here with a token inAuthorization. It is to the401(“I don’t know who you are,” lesson 3 of Phase 2) whatAllowis to the405(lesson 2 of Phase 2).await next(), at the end, is only reached with the right token.
The token, for now, is written in a separate file:
// The token that lets you create products. Written here only for now: in lesson 8 it will come// from an environment variable, because a secret should never be in the code.export const ADMIN_TOKEN = 'test-token-change-it';It’s a deliberate shortcut. A SecretA piece of data that gives access to something and that only the people and programs that need it should know, like a database password or an API key. It’s never written inside the code.Go to definition should never be in the code, because it ends up in Git and in every copy of the project. In lesson 8 you’ll read it from an Environment variableA name with a value, like PORT=3000, that a program receives when it starts from whoever starts it, for example the shell. It lets you configure the program without changing its code and give it secrets without writing them in it.Go to definition, as in lesson 7 of Phase 1.
Unlike the other two, this middleware doesn’t go with app.use. It goes on a single route, between the address and the function:
// adminOnly goes before the route's function: without the token, the route doesn't even run.app.post('/products', adminOnly, async (c) => { const data: { name: string; price: number } = await c.req.json(); const product = createProduct(data.name, data.price); return c.json(product, 201, { Location: `/products/${product.id}` });});app.post('/products', adminOnly, async (c) => …): Hono goes through adminOnly and, if it calls next(), through the function. GET /products has no guard and stays open. The function reads the 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 in the body, creates the product and answers 201 with Location, like POST /orders. It still trusts whatever arrives: a negative price would get through, and a body that isn’t JSON would end in a 500. Lesson 7, “Validation”, will fix that.
Order matters
Section titled “Order matters”Imagine Luis builds an admin panel on https://shop.example and decides that the whole API should ask for the token. He puts the guard on every route, but in front of CORS:
// Not like this: the guard before CORSapp.use(requestLog);app.use(adminOnly);app.use(cors({ origin: 'https://shop.example' }));With curl and the token, everything works. From the panel, it doesn’t. His fetch carries Authorization, so the browser asks first with a preflight request, and the preflight request never carries Authorization: the browser doesn’t send credentials just to ask. The guard stops it:
- adminOnlyno token
- adminOnly → requestLog401 Unauthorized
- corsnever runs
- requestLog → The browser401, without Access-Control-Allow-Origin
- The browserCORS error:
the real GET isn't sent
This is the preflight request, sent with curl, and its real response with the wrong order:
curl -i -X OPTIONS -H 'Origin: https://shop.example' -H 'Access-Control-Request-Method: GET' -H 'Access-Control-Request-Headers: Authorization' localhost:3000/ordersHTTP/1.1 401 Unauthorizedcontent-type: application/jsonwww-authenticate: BearerContent-Length: 37Date: Tue, 13 Oct 2026 11:19:08 GMTConnection: keep-aliveKeep-Alive: timeout=5
{"error":"A valid token is required"}Not a single access-control-* header: cors never even ran. With app.use(adminOnly) below cors, the same request gets a 204 with the permissions, because cors answers preflight requests before they reach the guard, and the GET with the token goes out afterward.
An order that works almost always:
- What has to see every request, like the request log.
- What answers anyone, like CORS preflight requests.
- The checks that may reject, like the token.
- The routes.
Try it
Section titled “Try it”The goal: get the API to log each request with how long it took, let Luis’s page read its responses and ask for the token to create products. Then you’ll break the order and find out which request disappears from the log.
You work in ~/backend-course/phase-3/shop-api, with the code from lesson 5. If you get stuck, download this lesson’s folder from ~/backend-course/phase-3 with curl -O https://backenddesdecero.com/practicas/shop-api/06-middleware.tar.gz, unpack it with tar -xzf 06-middleware.tar.gz, run npm install inside it and compare it with yours. If you use npm test, bring its test/ folder too: the one from lesson 5 still expects Allow: GET on /products.
Write the middleware
Section titled “Write the middleware”If you want your folder to end up like this lesson’s, start by removing the comparison from lesson 5:
1. Optional: remove Express and Fastify
npm uninstall express fastify @types/expressrm -r compare test/compare.test.tsWhat you will see:
removed 122 packages, and audited 7 packages in 699ms
found 0 vulnerabilitiesnpm uninstall deletes the packages from node_modules and from package.json, and rm -r deletes the folder and its test. If rm says No such file or directory, you no longer had them.
Now, the code. Create the folder with mkdir src/middleware and, inside it, request-log.ts and admin-only.ts, with the code from “How it really works”. Create src/config.ts too. In src/data.ts, add the function that saves a new product, a sibling of createOrder:
export function createProduct(name: string, price: number): Product { const product: Product = { id: products.length + 1, name, price }; products.push(product); return product;}It gives it the next number, adds it to the list and returns it. In src/app.ts, the imports end up like this:
import { Hono } from 'hono';import { cors } from 'hono/cors';import { createOrder, createProduct, findOrder, findProduct, orders, products } from './data.ts';import { adminOnly } from './middleware/admin-only.ts';import { requestLog } from './middleware/request-log.ts';Below export const app = new Hono();, the two app.use lines. After the GET /orders/:id route, the POST /products one. And since /products now accepts POST, its 405 has to say so:
// 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, POST' }));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' }));Call the API and look at the log
Section titled “Call the API and look at the log”You need two terminals: one for the server and another for curl. The outputs are from Node 26 on Linux; your dates and milliseconds will be different.
2. Start the server (first terminal)
npm run devWhat you will see:
> shop-api@1.0.0 dev> node --watch src/server.ts
The shop is listening on http://localhost:3000npm run dev starts node --watch, which restarts the server every time you save a file (lesson 4). Leave it open: the request log’s lines will show up here. If you get an error with Cannot find module, look at the file it names: either it doesn’t exist, or the import is missing its .ts at the end.
3. The list, from Luis's page (second terminal)
curl -i -H 'Origin: https://shop.example' localhost:3000/productsWhat you will see:
HTTP/1.1 200 OKaccess-control-allow-origin: https://shop.examplecontent-type: application/jsonvary: Origincontent-length: 108Date: Tue, 13 Oct 2026 11:19:01 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}]-H adds the Origin header the browser would send from Luis’s page. Notice access-control-allow-origin, the permission, and vary: Origin, which cors added on the way back. A new line has appeared in the first terminal:
GET /products 200 3 msIf it doesn’t appear, check that app.use(requestLog) is in app.ts and that you saved it.
4. From another origin
curl -i -H 'Origin: https://other.example' localhost:3000/productsWhat you will see:
HTTP/1.1 200 OKcontent-type: application/jsonvary: Origincontent-length: 108Date: Tue, 13 Oct 2026 11:19:01 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 whole list arrives, but without access-control-allow-origin: a browser on https://other.example would hide it. Phase 2’s nginx always sent the permission, with the shop’s origin; Hono’s middleware only sends it if the origin matches. The request log notes GET /products 200 0 ms.
5. The preflight request of a POST with JSON
curl -i -X OPTIONS -H 'Origin: https://shop.example' -H 'Access-Control-Request-Method: POST' -H 'Access-Control-Request-Headers: Content-Type' localhost:3000/ordersWhat you will see:
HTTP/1.1 204 No Contentaccess-control-allow-headers: Content-Typeaccess-control-allow-methods: GET,HEAD,PUT,POST,DELETE,PATCH,QUERYaccess-control-allow-origin: https://shop.examplevary: Origin, Access-Control-Request-HeadersDate: Tue, 13 Oct 2026 11:19:01 GMTConnection: keep-aliveKeep-Alive: timeout=5The same question you asked Phase 2’s nginx: “from the shop, can I send a POST with Content-Type?” cors answers, with a 204 and the permissions; the POST /orders route doesn’t run. In the request log: OPTIONS /orders 204 0 ms.
6. Create a product without a token
curl -i -X POST -H 'Content-Type: application/json' -d '{"name":"Cap","price":15}' localhost:3000/productsWhat you will see:
HTTP/1.1 401 Unauthorizedcontent-type: application/jsonvary: Originwww-authenticate: Bearercontent-length: 37Date: Tue, 13 Oct 2026 11:19:01 GMTConnection: keep-aliveKeep-Alive: timeout=5
{"error":"A valid token is required"}The guard answered 401 with www-authenticate: Bearer, and the cap wasn’t created. The request log sees this request too, because it’s outside the guard: POST /products 401 1 ms. If you get a 405, the POST /products route is missing or it’s below the app.all lines.
7. Now, with the token
curl -i -X POST -H 'Authorization: Bearer test-token-change-it' -H 'Content-Type: application/json' -d '{"name":"Cap","price":15}' localhost:3000/productsWhat you will see:
HTTP/1.1 201 Createdcontent-type: application/jsonlocation: /products/4vary: Origincontent-length: 32Date: Tue, 13 Oct 2026 11:19:01 GMTConnection: keep-aliveKeep-Alive: timeout=5
{"id":4,"name":"Cap","price":15}201 Created and location: /products/4: the cap is product 4, and curl localhost:3000/products/4 returns it. In the request log: POST /products 201 1 ms. With a single different character in the token, the 401 comes back.
Break the order
Section titled “Break the order”Change the order of the layers: in app.ts, put app.use(cors(…)) above app.use(requestLog) and save. In the first terminal, node --watch clears the screen and restarts:
Change detected in '/Users/ana/backend-course/phase-3/shop-api/src/app.ts'Restarting 'src/server.ts'The shop is listening on http://localhost:3000(On Linux and WSL, the path starts with /home/ana.) When it restarts, the cap disappears: the data lives in memory until Phase 5. Repeat the preflight request from step 5 and look at the first terminal.
Challenge: the response to step 5 comes out the same, with its 204 and its permissions, but no new line appears in the request log. A GET /orders, on the other hand, does show up. Why?Show answer
Now cors is the outer layer. It answers a preflight request by itself, without calling next(), so the request never reaches requestLog: it doesn’t see it come in or go out. The GET does go through, because with it cors calls next().
With this order, your request log would stop counting preflight requests, and if they failed one day, you wouldn’t see anything. The request log goes first to see them all. Put it back on top and save.
You have already seen it
Section titled “You have already seen it”- In Phase 2’s nginx. The
add_header Access-Control-Allow-Originlines and theif ($request_method = OPTIONS)block of the shop’s configuration did the work ofcors, and theaccess.logline per request, the work ofrequestLog. - In any Express tutorial. The
app.use(cors())andapp.use(express.json())lines at the start are middleware. Their shape is(req, res, next), andnext()doesn’t wait for the response: that’s why a request log likemorganuses another mechanism to see the finished response. - In DevTools (how to open them). In the Network tab, the
preflightrow of afetchwith JSON is the onecorsanswers without reaching your route. - On websites with “log in to continue”. Behind them there’s usually a middleware like
adminOnlyin front of every private route.
Common mistakes
Section titled “Common mistakes”- Forgetting the
awaitonnext(). The request log reads the code before the route answers: it writesGET /nothing 200 0 msfor a route that answers404. And if the route waits for something, Hono answers500and writes in the terminalContext is not finalized. Did you forget to return a Response object or `await next()`?. - Neither calling
next()nor returning anything. The request has nobody to answer it: the same500and the same error. - The guard before CORS. Preflight requests don’t carry
Authorization, and they get a401without permissions: “it works incurland not in the browser.” - A
401withoutWWW-Authenticate. The standard requires it: it says how to identify yourself. And if the caller has already identified themselves and doesn’t have permission, it isn’t a401, it’s a403. - Copying the check into every route. It works until someone adds a route and forgets it. With
app.use, the layer also covers tomorrow’s routes. - Leaving the token in the code. It’s fine for learning today; in lesson 8 it moves out of there. Never use this token for anything real: it’s published on this page.
Summary
Section titled “Summary”- A middleware is a function that receives the request and
next: it can answer by itself, pass it on withawait next()or do something before and after. - The lifecycle of a request: it comes in through the layers in the order of
app.use, reaches its route, and the response comes back through the same layers, in reverse. app.use(…)puts a layer in front of every request;app.post(route, middleware, function), in front of a single route.- CORS is a middleware: it adds the permissions and answers preflight requests without reaching the route. A guard that answers
401carriesWWW-Authenticate. - Order matters: the request log, first; CORS, before any check that may reject; the routes, last.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Middleware (Hono): the order of execution, with the onion drawing.
- CORS Middleware (Hono): all of
cors’s options, likeallowMethodsorcredentials. - WWW-Authenticate (MDN): the
401’s header and its schemes. - Using middleware (Express): the same concept in Express, with
(req, res, next).