Skip to article content
FrontendXLesson 06 / 24

Routing and middleware

Build a Node HTTP API from scratch, model data in SQL and MongoDB, and reason about transactions, indexes, caching and authentication so the endpoint you ship stays correct under load.

intermediate · about 50 minutes · 2 exercises

  • Predict
  • Implement

What you will be able to do

#
  • Explain a middleware chain and the role of next().
  • Order middleware so parsing, auth and handlers run in the right sequence.
  • Write an error-handling middleware that catches downstream failures.

Overview

#

A framework like Express runs a stack of middleware functions per request. Each function receives (req, res, next) and either ends the response or calls next() to continue. This is a pipeline, and order is behavior.

A correct order

snippet.js
app.use(express.json());          // parse body
app.use(requestLogger);           // log after body is available
app.use('/articles', requireAuth); // protect a subtree
app.get('/articles', listArticles);
app.post('/articles', createArticle);
app.use(notFound);                 // unmatched routes
app.use(errorHandler);             // four-argument error middleware last

Error middleware

snippet.js
function errorHandler(err, req, res, next) {
  const status = err.status || 500;
  if (status >= 500) console.error(err);
  res.status(status).json({ error: { code: err.code || 'server_error', message: err.expose ? err.message : 'Internal error' } });
}

Express detects error middleware by its four parameters. Async handlers must forward rejections with next(err) or a wrapper, otherwise the error escapes the chain.

Common pitfalls

  • Mounting express.json() after routes that need a parsed body.
  • Forgetting to call next() in a non-terminating middleware, which hangs the request.
  • Throwing inside an async handler without catching, which bypasses error middleware.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    A request hits a middleware that neither sends a response nor calls next(). What does the client observe?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.txt
    app.use((req, res, next) => {
      if (req.headers['x-debug']) {
        // intended to continue, but next() is missing
      }
    });
    Choose the best answer
  2. Exercise 2Implement

    Write an async wrapper so a rejected handler promise reaches error middleware.

    starter.javascript
    function asyncHandler(fn) {
      // return a middleware that forwards rejections to next
    }
    

    Reveal the reference answer
    reference.javascript
    function asyncHandler(fn) {
      return (req, res, next) => {
        Promise.resolve(fn(req, res, next)).catch(next);
      };
    }

    Authored expected output: A middleware that calls next(err) when the wrapped async handler rejects.

    Wrapping the handler and attaching .catch(next) converts a rejected promise into a chain error that error middleware can handle.

Common misconceptions

#
  • Middleware order does not matter: the first middleware that ends the response wins, so order changes behavior.
  • Async errors are caught automatically: without a wrapper or next(err), a rejected promise is an unhandled rejection.

Follow-up practice

#
  • backend-databases-config-secrets

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.