Not Found Handler
The Not Found Handler component provides a centralized and consistent way to handle unmatched routes.
Instead of allowing undefined routes to return inconsistent responses or default Express errors, this component ensures that all unknown endpoints respond with a standardized 404 Not Found error.
This component exists to:
- Catch all requests to undefined routes
- Return a predictable and structured 404 response
- Integrate seamlessly with ServerCN error handling
- Improve API reliability and developer experience
Installation Guide
This component requires additional ServerCN components.
👉 Note: You do not need to install any servercn dependencies manually. Installing this component will automatically install all required servercn dependencies. Manual installation is optional if you prefer to manage dependencies yourself.
1. Install ServerCN dependencies(Optional)
- API Error Handler:
npx servercn add error-handlerDocumentation: API Error Handler
⚠️ If this dependency is not installed, the component will not function correctly.
2. Install this component
npx servercn add not-found-handlerThis component requires the API Error Handler component to function correctly.
Basic Implementation
The Not Found Handler is a middleware that catches all unmatched routes and throws a standardized 404 error.
1. MVC Structure
src/middlewares/not-found-handler.ts
import { Request, Response, NextFunction } from "express";
import { ApiError } from "../utils/api-error";
export const notFoundHandler = (
req: Request,
res: Response,
next: NextFunction
) => {
throw ApiError.notFound(`Route ${req.method} ${req.originalUrl} not found`);
};2. Feature Structure
src/shared/middlewares/not-found-handler.ts
import { Request, Response, NextFunction } from "express";
import { ApiError } from "../errors/api-error";
export const notFoundHandler = (
req: Request,
res: Response,
next: NextFunction
) => {
throw ApiError.notFound(`Route ${req.method} ${req.originalUrl} not found`);
};Usage Example
The Not Found Handler must be placed after all routes but before the error handler in your Express application.
1. MVC Structure
src/app.ts
import express, { type Application } from "express";
import "dotenv/config";
import { errorHandler } from "./middlewares/error-handler";
import { notFoundHandler } from "./middlewares/not-found-handler";
const app: Application = express();
app.use(express.json());
// routes here
// ...
// Not found handler (should be after routes)
app.use(notFoundHandler);
// Global error handler (should be last)
app.use(errorHandler);
export default app;2. Feature Structure
src/app.ts
import express, { type Application } from "express";
import "dotenv/config";
import { errorHandler } from "./shared/middlewares/error-handler";
import { notFoundHandler } from "./shared/middlewares/not-found-handler";
const app: Application = express();
app.use(express.json());
// routes here
// ...
// Not found handler (should be after routes)
app.use(notFoundHandler);
// Global error handler (should be last)
app.use(errorHandler);
export default app;Response Format
When a route is not found, the handler returns a standardized 404 response:
{
"success": false,
"message": "Route GET /api/v1/invalid-route not found",
"statusCode": 404
}The exact format depends on your ApiError and ApiResponse configuration.
How It Works
- Route Matching: Express processes routes in the order they are defined
- Catch-All: The Not Found Handler is placed after all defined routes
- Error Throwing: When a request doesn't match any route, it reaches the Not Found Handler
- Error Propagation: The handler throws an
ApiErrorwith a 404 status code - Error Handling: The global error handler catches the error and returns a standardized response
Best Practices
- Use
ApiError.notFound()for consistency - Always place the Not Found Handler after all route definitions
- Always place the Not Found Handler before the global error handler
- The handler will catch all HTTP methods (GET, POST, PUT, DELETE, etc.)
- Customize the error message to include the method and path for better debugging
Why This Component Matters
Without a dedicated not found handler:
- Undefined routes may return HTML error pages
- Error responses become inconsistent
- Debugging API issues becomes harder
This component ensures:
- All API endpoints return JSON
- Status codes are correct and explicit
- Errors are handled uniformly