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
- Define all your application routes first.
- After all routes, add:
app.use((req, res) => { res.status(404).send('Not Found'); });. - For APIs, return JSON:
res.status(404).json({ error: 'Resource not found' });. - For HTML responses, render a 404 template:
res.status(404).render('404');. - 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.