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 after all routes that catches requests not matched by any route using 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.

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 no response or a hanging request, causing confusion.
🔧

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.

javascript
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');
});
Output
Requesting any URL other than '/' responds with '404: Page not found' and HTTP status 404.
🛡️

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.

Key Takeaways

Add a 404 middleware after all routes using app.use to catch unmatched requests.
Set response status to 404 and send a clear message to inform users.
Place the 404 handler last to avoid blocking valid routes.
Log 404 errors to track missing pages and improve your app.
Use error-handling middleware for other HTTP errors like 500 or 403.