Middleware
Understand the idea
Middleware is a function that runs between the request and the response, and order is the behavior.
The idea
Each app.use function receives req, res, and next. Calling next hands the same request to the next function. Sending a response ends the chain. The route at the bottom runs only if every middleware before it called next.
What changes
| Registered first | What runs | Body |
|---|---|---|
| log, then auth | log and auth | log,auth |
| auth, then log | auth only | auth |
| A route after a finished response | Nothing | The route text never appears |
The command
Logger then auth
3s timeout · one stateless run. Node and Express use Piston when that instance accepts the job (public EMKC execute is whitelist-only; set PISTON_URL or PISTON_TOKEN). Otherwise a local Node process. MongoDB uses a fresh in-memory server per run, then it is stopped.
Auth then logger
3s timeout · one stateless run. Node and Express use Piston when that instance accepts the job (public EMKC execute is whitelist-only; set PISTON_URL or PISTON_TOKEN). Otherwise a local Node process. MongoDB uses a fresh in-memory server per run, then it is stopped.
The mistake
Check the result
The first body is log,auth. The second body is auth. Neither body starts with route, because auth ended the response.
Guided challenge
Put auth before the logger
The starter registers the logger first, then auth. Swap the two app.use blocks so auth runs first and ends with 401 before the logger can push log.
Put auth before the logger
3s timeout · one stateless run. Node and Express use Piston when that instance accepts the job (public EMKC execute is whitelist-only; set PISTON_URL or PISTON_TOKEN). Otherwise a local Node process. MongoDB uses a fresh in-memory server per run, then it is stopped.
EXPECTED RESULT
status 401 auth
Hints 0/2
Use all hints or make 3 failed checks (0/3).
Free exploration
Change this example and run it again. Each run is a new process. Nothing is saved.
Your variation
3s timeout · one stateless run. Node and Express use Piston when that instance accepts the job (public EMKC execute is whitelist-only; set PISTON_URL or PISTON_TOKEN). Otherwise a local Node process. MongoDB uses a fresh in-memory server per run, then it is stopped.
Quiz
A quick check for understanding. Retry as often as you like; your learning path stays open.
Ready to call this one understood?
Mark this lesson complete to earn 150 XP. You can always revisit it.