Node.js › Error Handling

How would you implement a global 'not found' (404) handler in Express for any route that doesn't match a defined endpoint?

Intermediate

Answer

A catch-all middleware placed after all defined routes (but before the error-handling middleware) matches any request that hasn't already been handled by an earlier route, letting the application return a consistent, well-formatted 404 response rather than Express's default plain-text 'Cannot GET /some/path' message.
// After all your defined routes
app.use((req, res) => {
  res.status(404).json({ error: 'Not Found', path: req.originalUrl });
});

// Error-handling middleware still goes after this
app.use((err, req, res, next) => { /* ... */ });
Real-world example An API that previously returned Express's default plain-text 404 page adds a catch-all JSON 404 handler, ensuring every unmatched route (a typo'd endpoint, a deprecated API version) returns a consistent, machine-parseable JSON error response matching the rest of the API's error format.

Common follow-ups: Why must this catch-all handler be placed after every other route definition to work correctly?;How would you distinguish a genuinely undefined route from a route that exists but the specific resource ID wasn't found?