Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

NO
Node.js & Express
0/13 completed
Beginner
What is Node.js?Modules and npmWorking with filesCallbacks, promises and the event loop
Intermediate
Events and streamsYour first HTTP serverExpress basicsRouting and middlewareConnecting a database
Advanced
Validation and configurationAuthentication with JWTTesting APIs
Pro
Deploying Node apps to production
Tracks / Node.js & Express / Intermediate

Routing and middleware

The real power of Express is middleware: small functions that every request flows through on its way to your route. Logging, parsing bodies, checking logins, adding security headers and handling errors are all middleware.

What middleware is

A middleware function receives req, res and next. It can read or change the request, send a response itself, or call next() to pass control to the next function in line:

request → [logger] → [express.json] → [auth check] → [route handler] → response
Node.js · editable

If a middleware neither sends a response nor calls next(), the request hangs forever. Every middleware must do one or the other.

Middleware for some routes only

Middleware can be attached to a path prefix or to individual routes:

Node.js · editable

Routers: organising a bigger app

As an app grows, put related routes in an express.Router() in its own file, and mount it under a prefix:

Node.js · editable

A common project layout:

src/
├── app.js            creates the app, adds middleware, mounts routers
├── server.js         imports app and calls app.listen()
├── routes/           one router per resource (users.js, orders.js)
├── middleware/       auth.js, errors.js, validate.js
└── services/         business logic and database access

Keeping app (configuration) separate from server (listening) makes the app easy to test, as you'll see in the testing lesson.

Error handling

Middleware with four parameters, (err, req, res, next), is an error handler. Express sends errors to it when a route throws or calls next(err):

Node.js · editable
  • Express 5 catches errors in async handlers automatically: a rejected promise goes to your error handler. (In Express 4 you had to wrap async handlers or call next(err) yourself.)
  • Never send internal details (stack traces, SQL errors) to clients. Log them on the server, and send a generic message.
  • Put the 404 handler and the error handler after all routes.

Popular middleware packages

Node.js · editable
Package Purpose
helmet Sets security headers (and removes X-Powered-By)
cors Allows browsers on other domains to call your API
morgan Logs each request
cookie-parser Parses cookies into req.cookies
express-rate-limit Limits requests per client to stop abuse
compression Gzips responses

Practice

  1. Write a timing middleware that adds an X-Response-Time header with the time the request took.
  2. Create a products router with GET / and GET /:id and mount it at /api/products.
  3. Make the error handler return { "error": …, "path": … } and log 500 errors with the request method and URL.
✎ Check your understanding

1.What must a middleware function do if it doesn't send a response?

2.How does Express recognise an error-handling middleware?

3.In Express 5, what happens when an async route handler throws?

← Express basics