How to Handle 404 Errors in Express: Simple Guide
app.use. This middleware should send a 404 status and a helpful message to the client.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 not respond properly, leaving the user confused or the request hanging.
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 all your routes that catches any request not handled earlier. This middleware sets the response status to 404 and sends a clear message to the user.
import express from 'express'; const app = express(); app.get('/', (req, res) => { res.send('Home page'); }); // 404 handler middleware app.use((req, res) => { res.status(404).send('Sorry, page not found'); }); app.listen(3000, () => console.log('Server running on port 3000'));
Prevention
Always place your 404 handler middleware after all route definitions to catch unmatched requests. Use clear messages or custom 404 pages to improve user experience. Consider logging 404 errors to monitor broken links or user mistakes.
Use linting tools and code reviews to ensure the 404 middleware is not accidentally omitted or placed too early.
Related Errors
Other common errors include 500 Internal Server Errors caused by server bugs, and 403 Forbidden errors when users try to access restricted pages. Handling these with proper middleware and error handlers improves app reliability.