0
0
Expressframework~8 mins

404 Not Found handler in Express - Performance & Optimization

Choose your learning style9 modes available
Performance: 404 Not Found handler
MEDIUM IMPACT
This affects the server response time and user experience when a requested resource is missing.
Handling requests for missing pages
Express
const path = require('path');
app.use((req, res) => {
  res.status(404).sendFile(path.join(__dirname, 'public', '404.html'));
});
Serves a static 404 page file, allowing caching and faster response without blocking event loop.
📈 Performance GainNon-blocking file streaming; leverages browser caching; reduces server CPU usage.
Handling requests for missing pages
Express
app.use((req, res) => {
  res.status(404).send('<html><body><h1>Page not found</h1></body></html>');
});
Sends a full HTML string inline, which can be bulky and blocks the event loop if complex logic is added.
📉 Performance CostBlocks event loop briefly for string construction; no caching or streaming used.
Performance Comparison
PatternServer CPU UsageResponse TimeCachingVerdict
Inline HTML string in handlerHigh (blocks event loop if complex)Slower (builds string every request)No caching[X] Bad
Serve static 404 HTML fileLow (non-blocking streaming)Faster (cached by browser/server)Yes, effective caching[OK] Good
Rendering Pipeline
When a 404 handler runs, the server prepares a response which the browser then parses and renders. Efficient handlers minimize server delay and reduce time to first byte, improving the Largest Contentful Paint.
Server Response
Network Transfer
Browser Parsing
Rendering
⚠️ BottleneckServer Response preparation if handler is slow or blocking
Core Web Vital Affected
LCP
This affects the server response time and user experience when a requested resource is missing.
Optimization Tips
1Serve static 404 pages to leverage caching and reduce server CPU load.
2Avoid building large HTML strings inline in the 404 handler to prevent blocking.
3Ensure 404 responses are fast to improve Largest Contentful Paint (LCP).
Performance Quiz - 3 Questions
Test your performance knowledge
What is a performance benefit of serving a static 404 page file instead of inline HTML in Express?
AIt blocks the event loop longer but improves rendering.
BIt increases server CPU usage but reduces network size.
CIt allows browser caching and reduces server CPU usage.
DIt disables browser caching to ensure fresh content.
DevTools: Network
How to check: Open DevTools, go to Network tab, request a missing page, and inspect the 404 response headers and timing.
What to look for: Look for fast Time to First Byte (TTFB) and presence of cache headers indicating static file serving.