How do you return a custom 404 response for unknown routes in Express?
Add a middleware with no path after all your routes. If no earlier route replied, the request reaches it, and you send a 404 status with a JSON or HTML body.
Explain it simply
At a railway enquiry desk, if none of the specific counters can help you, the last counter says, "No such train." The 404 handler is that last counter. It works only because it sits at the end: any request that no earlier route answered falls through to it.
Example
const express = require("express");
const app = express();
app.get("/api/notices", (req, res) => res.json([]));
// 404 handler: no path, registered after every route
app.use((req, res) => {
res.status(404).json({
error: "Not found",
path: req.originalUrl,
});
});
// optional: error handler after it
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: "Internal server error" });
});
app.listen(3000);Points to know:
- Express has a default 404 page, but it is plain HTML, which is awkward for an API client expecting JSON.
- A 404 is not an error to Express: nothing throws. The error handler runs only when
next(err)is called. - For a missing resource inside a route, such as a student ID that is not in the database, reply with 404 right there.
- A single-page app often sends
index.htmlfor unknown non-API paths instead.
What to say in the interview
"I add a catch-all middleware after the routes that responds with 404 and a JSON body. Then comes the error handler for real failures. The order is what makes the fallback work."
Common mistakes
- Putting the catch-all above the routes, which makes every request return 404.
- Returning 200 with an error message for a missing resource.