Table Of Contents
Problem
You need to handle routes that don't exist in your Express.js application and return a custom 404 response instead of the default "Cannot GET /path" error.
Solution
const express = require('express');
const app = express();
// Your regular routes
app.get('/', (req, res) => {
res.send('Home page');
});
app.get('/about', (req, res) => {
res.send('About page');
});
// 404 handler - must be last
app.use((req, res) => {
res.status(404).json({
error: 'Page not found',
message: `Cannot ${req.method} ${req.path}`,
statusCode: 404
});
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Explanation
The app.use()
middleware without a path acts as a catch-all for any request that doesn't match your defined routes. Since Express processes middleware in order, placing this at the end ensures it only runs when no other route matches.
The res.status(404)
sets the HTTP status code, and you can return JSON, HTML, or render a template as needed. For HTML responses, use res.send()
with HTML content or res.render()
with a template engine.
Share this article
Add Comment
No comments yet. Be the first to comment!