Performance: 404 Not Found handler
This affects the server response time and user experience when a requested resource is missing.
const path = require('path'); app.use((req, res) => { res.status(404).sendFile(path.join(__dirname, 'public', '404.html')); });
app.use((req, res) => {
res.status(404).send('<html><body><h1>Page not found</h1></body></html>');
});| Pattern | Server CPU Usage | Response Time | Caching | Verdict |
|---|---|---|---|---|
| Inline HTML string in handler | High (blocks event loop if complex) | Slower (builds string every request) | No caching | [X] Bad |
| Serve static 404 HTML file | Low (non-blocking streaming) | Faster (cached by browser/server) | Yes, effective caching | [OK] Good |
404 Not Found handler in an Express app?app.use with (req, res) parameters, no error parameter.app.use with (req, res) and sets status 404. app.get('/404', (req, res) => { res.send('Not Found'); }); is a route, not a catch-all. app.use((err, req, res, next) => { res.status(404).send('Not Found'); }); is an error handler (has err param). app.route('*').get((req, res) => { res.status(404).send('Not Found'); }); uses app.route('*') which is not standard for 404./unknown?
const express = require('express');
const app = express();
app.get('/home', (req, res) => {
res.send('Welcome Home');
});
app.use((req, res) => {
res.status(404).send('Page Not Found');
});
app.listen(3000);app.use middleware catches all unmatched routes and sends 'Page Not Found' with status 404.app.use((req, res, next) => {
res.send('404 Not Found');
res.status(404);
});res.send sends the response immediately. Setting status after sending has no effect.res.send to apply correctly.app.use with (req, res), no error parameter.Pass the test and this pattern moves unknown