How to handle 404 errors in Express

· Category: Node.js

Short answer

Add a catch-all middleware at the end of your route definitions that sends a 404 status and a custom message or page.

Steps

  1. Define all your application routes first.
  2. After all routes, add: app.use((req, res) => { res.status(404).send('Not Found'); });.
  3. For APIs, return JSON: res.status(404).json({ error: 'Resource not found' });.
  4. For HTML responses, render a 404 template: res.status(404).render('404');.
  5. Keep this handler after all other app.use() calls but before error-handling middleware.

Tips

  • Log 404 occurrences to detect broken links or scanning attempts.
  • Return different formats based on req.accepts('json') versus HTML for versatile APIs.

Common issues

  • If placed before some routes, the catch-all will intercept valid requests. Always define it last among route handlers.
  • Static file middleware can also generate implicit 404s if files are missing.