0
0
ExpressDebug / FixBeginner · 3 min read

How to Fix 404 Error in Express: Simple Steps

A 404 error in Express happens when no route matches the request URL. To fix it, add a catch-all middleware with 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.

javascript
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'));
Output
Requesting any path other than '/home' returns a 404 Not Found error.
🔧

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.

javascript
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'));
Output
Requesting '/home' returns 'Welcome Home'. Requesting any other path returns 'Sorry, page not found' with status 404.
🛡️

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.

Key Takeaways

A 404 error means no route matched the request URL in Express.
Add a catch-all middleware with app.use at the end to handle unmatched routes.
Always define routes clearly and test them to avoid 404 errors.
Place the 404 handler after all other routes to ensure it catches only unmatched requests.
Use linters and testing to prevent routing mistakes.