How to Fix 404 Error in Express: Simple Steps
app.use after all routes to handle unmatched requests and send a 404 response.Why This Happens
A 404 error occurs when Express cannot find a route that matches the requested URL. This usually happens if you forget to define a route for that path or if the route order is incorrect.
import express from 'express'; const app = express(); app.get('/home', (req, res) => { res.send('Welcome Home'); }); app.listen(3000, () => console.log('Server running on port 3000'));
The Fix
Add a catch-all middleware at the end of your route definitions to handle any requests that don't match existing routes. This middleware sends a 404 status and a friendly message.
import express from 'express'; const app = express(); app.get('/home', (req, res) => { res.send('Welcome Home'); }); // Catch-all 404 handler app.use((req, res) => { res.status(404).send('Sorry, page not found'); }); app.listen(3000, () => console.log('Server running on port 3000'));
Prevention
Always define routes for all expected URLs and place the 404 catch-all middleware last. Use tools like linters to warn about unreachable routes. Testing your routes regularly helps catch missing paths early.
Related Errors
Other common errors include 500 Internal Server Error caused by server bugs, and 403 Forbidden when access is denied. For 500 errors, check your error handling middleware. For 403, verify user permissions.