0
0
Expressframework~5 mins

404 Not Found handler in Express

Choose your learning style9 modes available
Introduction

A 404 Not Found handler tells the user when they try to visit a page that does not exist on your website.

When a user types a wrong URL on your website.
When a link points to a page that has been removed.
When a user tries to access a page that you never created.
To improve user experience by showing a friendly message instead of a blank page.
To help search engines understand that the page is missing.
Syntax
Express
app.use((req, res, next) => {
  res.status(404).send('Page not found');
});

This middleware runs after all other routes have been checked.

It sets the HTTP status code to 404 and sends a message to the user.

Examples
Sends a custom message for missing pages.
Express
app.use((req, res) => {
  res.status(404).send('Sorry, this page does not exist.');
});
Sends a JSON response instead of plain text, useful for APIs.
Express
app.use((req, res) => {
  res.status(404).json({ error: 'Not Found' });
});
Renders a 404 page using a template engine like Pug or EJS.
Express
app.use((req, res) => {
  res.status(404).render('404');
});
Sample Program

This simple Express app has one route for the homepage. If you visit any other URL, the 404 handler sends a friendly message.

Express
import express from 'express';

const app = express();

app.get('/', (req, res) => {
  res.send('Welcome to the homepage!');
});

// 404 Not Found handler
app.use((req, res) => {
  res.status(404).send('Oops! Page not found.');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Always place the 404 handler after all other routes.

Use res.status(404) to set the correct HTTP status code.

You can customize the message or render a page for better user experience.

Summary

A 404 handler catches requests to unknown pages.

It improves user experience by showing a clear message.

Place it last in your route list to work correctly.