Blog>
Snippets

Handling 404 and Error Pages

Customize 404 and error pages using the App Router by creating special route files that handle not found and error states.
const express = require('express');
const app = express();

// Serve static files
app.use(express.static('public'));

// Define a catch-all route for 404 Not Found
app.use((req, res, next) => {
  res.status(404).send('404: Page Not Found');
});

// Global error handler for other types of errors
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => { 
  console.log(`Server running on port ${PORT}`);
});
This code snippet sets up an Express.js application with custom 404 and error handling. The app serves static files from the 'public' directory. It defines a custom 404 handler for any undefined routes and a global error handler for other errors.