Express.js, step by step
Everything a junior or fresher usually gets asked about Express.js, in simple English. Read a topic, look at the code, then tick “I understand this topic”.
Practice Q&A
Try to answer in your own words first, then open the answer. Mark the questions you know. Your progress is saved in this browser.
Diagrams
Pictures make Express easier to remember. Most interview answers about middleware, routing and errors become simple once you can “see” the request moving.
1 · Where Express fits
Express is not a server by itself. It runs inside Node.js and handles the requests that Node gives it.
- Node opens the port and receives the raw HTTP request.
- Express gets
reqandresobjects and runs your middleware and routes. - Your code talks to the database and sends a response back the same way.
2 · Life of one request
A request goes through a list of middleware, then reaches the route handler, then a response goes back.
- Each yellow box calls
next()to pass the request on. - Any box can stop the chain by sending a response (for example
protectsends 401). - Only one response is allowed per request.
3 · The middleware chain and next()
Three possible paths: go to the next function, stop early with a response, or jump to the error handler.
- Solid grey arrow —
next()moves to the next function. - Dashed grey arrow — a middleware ends the request early by sending a response.
- Red dashed arrow —
next(err)(or a thrown error) skips every normal middleware and goes to the error handler.
4 · Route order: top to bottom, first match wins
Request: GET /users/me
GET /usersno matchGET /users/:idMATCH — id = "me"GET /users/menever reachedThe dynamic route catches “me” as if it were an id, and the correct route never runs.
GET /usersno matchGET /users/meMATCH — runs getMe()GET /users/:idnot checkedPut specific routes first and dynamic routes after them.
5 · Project layers (routes → controller → service → model)
Each layer has one job. This keeps the code easy to read and to test.
Two entry files
module.exports = appapp.listen()app only (Supertest) — no real port- Controllers stay thin. Services hold the logic.
- Errors from any layer go to one central error handler.
6 · Login and a protected route (JWT)
First the user logs in and gets a token. After that, every request carries the token.
- At step 7, a missing, wrong or expired token gives 401 and the route handler never runs.
- A
restrictTo('admin')middleware afterprotectwould return 403 if the role is wrong.
7 · Error handling flow
There is one normal path and two ways to reach the error handler.
Normal path
Path 1 — nothing matched (404)
Path 2 — something throws or calls next(err)
- The error handler is the last
app.use()in the file. - Express 4: in async code, you must call
next(err)yourself (or use a wrapper). Express 5: a rejected promise does this for you. - For unexpected (500) errors, log the real error and send a short, safe message to the client.