HomebaseWorks
Lesson 2 of 4

Express routing, middleware, errors and config

Follow a request through Express middleware, handle errors in one place, and keep configuration in environment variables.

EWritten by the HomebaseWorks editorial team · reviewed 26 Oct 2026

An Express app is a list of functions that a request passes through in order. Once you see it as a pipeline, questions about hanging requests, missing routes and error handling become easy to reason about.

Advertisement

Middleware order

Every middleware receives req, res and next, and must either send a response or call next(). Forget both and the request hangs. Order matters: express.json() must be registered before routes that read req.body, and an authentication check must come before the routes it protects.

app.use(express.json());
app.use('/admin', requireLogin);
app.get('/admin/users', listUsers);

Routes and parameters

Route paths can include parameters, such as /users/:id, available as req.params.id. Query strings appear in req.query. Both are always strings, so convert and validate them. Return clear status codes: 400 for bad input, 401 when not logged in, 403 when logged in but not allowed, 404 when not found.

Central error handling

Error-handling middleware has four parameters and goes after all routes:

app.use((err, req, res, next) => {
  console.error(err);
  res.status(err.status || 500).json({ error: 'Something went wrong' });
});

Pass errors to it with next(err). In Express 4, an error thrown inside an async route is not caught automatically, so wrap the body in try/catch and call next(err), or use a small wrapper; Express 5 forwards rejected promises for you. Do not send stack traces to clients in production.

Environment variables

Keep ports, database URLs and API keys out of the code and read them from process.env. Values are always strings, so Number(process.env.PORT) || 3000 is safer than using the raw value. Local .env files are convenient, but add them to .gitignore so secrets never reach the repository.

Checklist: for each new route, confirm that every path through it sends exactly one response or calls next, and that inputs are validated before use.

Advertisement
Continue with Node.js4 lessons · 1 interview set · 1 test · 1 certificate
Not tested

More in Web and app