How can you serve a custom HTML page for 404 errors in an Express.js application?

Question

Grade: Education Subject: Support
How can you serve a custom HTML page for 404 errors in an Express.js application?
Asked by:
81 Viewed 81 Answers

Answer (81)

Best Answer
(530)
To serve a custom HTML page for 404 errors, first, ensure you have a templating engine (like Pug, EJS, Handlebars) configured or a static HTML file. Then, in your 404 middleware, you would set the status and render or send the file. For example, using a templating engine: `app.use((req, res, next) => { res.status(404).render('404', { title: 'Page Not Found', path: req.originalUrl }); });`. If serving a static HTML file: `app.use((req, res, next) => { res.status(404).sendFile(path.join(__dirname, 'public', '404.html')); });`.