Node.js Developer interview question · Most asked

Walk through how an Express app handles a request, including errors from async handlers.

Summary

Middleware and routes run in registration order; each either responds or calls next(). next(err), or a synchronous throw, skips to error-handling middleware, which Express recognises by its four parameters. If nothing responds, Express returns 404. Express 4 ignores rejected promises from async handlers (the request hangs and an unhandledRejection is logged); Express 5 forwards them to the error handlers.

Longer Answer

Register error handlers last, declare them with all four parameters, and return after sending a response to avoid 'Cannot set headers after they are sent'. In Express 4, wrap async handlers so rejections call next(err), or upgrade to Express 5.

Code Example

// Express 4: forward async errors explicitly
const wrap = (fn) => (req, res, next) => fn(req, res, next).catch(next);
app.get("/orders", wrap(async (req, res) => res.json(await db.orders())));

app.use((err, req, res, next) => {              // four parameters = error handler
  res.status(500).json({ error: "internal", requestId: req.id });
});

Key Points

  • Registration order; next() continues.
  • Error handlers have four parameters.
  • Express 4 ignores rejected promises; Express 5 forwards them.
  • Never respond twice.

Deep dive: Request Lifecycle course: Express: The Middleware Stack and Error Handling

Explanation

What interviewers look for

The arity rule and the Express 4 vs 5 async difference.

More most-asked Node.js Developer questions

← All Node.js Developer questions