0
0
ExpressDebug / FixBeginner · 3 min read

How to Handle 404 Errors in Express: Simple Guide

In Express, handle 404 errors by adding a middleware at the end of your routes that catches requests not matched by any route using 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.

javascript
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'));
Output
Requesting any URL other than '/' results in a 404 response with the default Express message.
🔧

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.

javascript
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'));
Output
Requesting any unknown URL returns a 404 status with the message: 'Sorry, page not found'
🛡️

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.

Key Takeaways

Place a 404 middleware after all routes to catch unmatched requests.
Set response status to 404 and send a clear message to users.
Use logging to track 404 errors and improve your app.
Always test routes to ensure 404 handling works as expected.