How to Handle 404 Errors in Express: Simple Guide
app.use. This middleware should send a 404 status and a message to inform users the page was not found.Why This Happens
A 404 error happens when a user requests a page or resource that your Express app does not have a route for. If you don't handle this case, the server will just hang or send a default empty response, confusing users.
import express from 'express'; const app = express(); app.get('/', (req, res) => { res.send('Home page'); }); app.listen(3000, () => { console.log('Server running on port 3000'); });
The Fix
Add a middleware at the end of your route definitions that catches all unmatched requests. This middleware sets the HTTP status to 404 and sends a clear message. This tells users the page was not found.
import express from 'express'; const app = express(); app.get('/', (req, res) => { res.send('Home page'); }); // 404 handler middleware app.use((req, res, next) => { res.status(404).send('404: Page not found'); }); app.listen(3000, () => { console.log('Server running on port 3000'); });
Prevention
Always add a 404 handler middleware after all your routes to catch unmatched requests. Use clear messages to help users understand the error. Consider logging 404 errors to monitor broken links. Use tools like linters or route tests to ensure all expected routes exist.
Related Errors
Other common errors include 500 Internal Server Errors caused by bugs in route handlers, and 403 Forbidden errors when users lack permission. Handling these requires error-handling middleware with app.use((err, req, res, next) => { ... }) to catch and respond properly.