How to handle unknown routes — Basic
Register a notFound middleware after all routes to return a consistent 404 response.
Learn: If no route matched, Express falls through to the next middleware. Register notFound after all routers so clients get a consistent JSON 404 instead of a generic HTML page.
Supplementary examples
notFound middleware
function notFound(req, res, next) {
res.status(404).json({ error: `Not found: ${req.method} ${req.originalUrl}` });
}
// in app.js, after all routes:
app.use(notFound);Course example
const express = require("express");
const cors = require("cors");
const app = express();
const corsEnabledRouter = require("./cors-enabled/cors-enabled.router");
const corsNotEnabledRouter = require("./cors-not-enabled/cors-not-enabled.router");
const notFound = require("./errors/notFound");
const errorHandler = require("./errors/errorHandler");
app.use(cors());
app.use(express.json());
app.use("/cors-enabled", corsEnabledRouter);
app.use("/cors-not-enabled", corsNotEnabledRouter);
app.use(notFound);
app.use(errorHandler);
module.exports = app;
Additional references & examples
- Express.js guide
Routing, middleware order, and request/response lifecycle.
- HTTP status codes (MDN)
When to use 200, 201, 204, 400, 404, 500, and related codes.