Handling 404 Errors in Express.js


Handling 404 Errors in Express.js

In Express.js, when a client requests a route that doesn’t exist, a 404 error (Not Found) should be returned. By default, if a route is not found, the server will hang without returning a meaningful response unless you handle the 404 error explicitly.

To handle 404 errors in Express, you can define a middleware function that catches all unmatched routes and returns a 404 response.

Steps to Handle 404 Errors

1. Define a 404 Middleware

To handle 404 errors, add a middleware function after all your route definitions. This middleware will be triggered when no route matches the incoming request.

Example:

const express = require('express'); const app = express(); // Define routes app.get('/', (req, res) => { res.send('Home Page'); }); app.get('/about', (req, res) => { res.send('About Page'); }); // 404 Error Handling Middleware (Must be placed after all routes) app.use((req, res, next) => { res.status(404).send('Sorry, page not found'); }); app.listen(3000, () => { console.log('Server running on port 3000'); });

In this example:

  • If a user visits /, they’ll see the home page.
  • If they visit /about, they’ll see the about page.
  • If they visit any other route (e.g., /contact), the middleware at the end will catch it and respond with 404 and the message Sorry, page not found.

2. Using res.status() and res.send()

The res.status(404) sets the HTTP status code to 404, and res.send() sends the response back to the client. You can also use res.json() to return JSON or res.render() to return an HTML template.

Example with JSON:

app.use((req, res, next) => { res.status(404).json({ error: 'Not Found' }); });

Example with an HTML Template:

If you are using a view engine like EJS, you can render an HTML template for the 404 error page.

app.use((req, res, next) => { res.status(404).render('404', { title: '404 - Not Found' }); });

3. Handling Other Errors

In addition to 404 errors, you can handle other types of errors like server errors (500 Internal Server Error) using an error-handling middleware function.

Example of General Error Handling Middleware:

// General error handling middleware app.use((err, req, res, next) => { console.error(err.stack); // Log the error res.status(500).send('Something went wrong!'); });

This middleware handles any errors that occur in the application and returns a 500 status with a generic error message.

4. Middleware Ordering Matters

It's crucial that the 404 error-handling middleware is defined after all other routes and middleware. This ensures that it only triggers if no other route matches the request.

If the 404 middleware is defined too early, it might prevent legitimate routes from being matched.

Full Example of 404 and Error Handling:

const express = require('express'); const app = express(); // Define routes app.get('/', (req, res) => { res.send('Home Page'); }); app.get('/about', (req, res) => { res.send('About Page'); }); // 404 handler app.use((req, res, next) => { res.status(404).send('Sorry, page not found'); }); // General error handler app.use((err, req, res, next) => { console.error(err.stack); // Log the error res.status(500).send('Something went wrong!'); }); app.listen(3000, () => { console.log('Server running on port 3000'); });

Summary

  • 404 Error Handling: A 404 error occurs when no defined route matches the requested URL.
  • 404 Middleware: Define a middleware function that sets the status to 404 and returns a custom message or view. Place this middleware after all route handlers.
  • General Error Handling: Use an error-handling middleware to catch server-side errors (e.g., 500 errors) and respond appropriately.
  • Middleware Order: The order of middleware and route definitions matters. The 404 middleware must come after all valid routes to ensure it only triggers for undefined routes.

By handling 404 errors, you improve user experience by providing meaningful feedback when users access invalid URLs.