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.

  • API Error Handler:
npx servercn add error-handler

Documentation: API Error Handler

⚠️ If this dependency is not installed, the component will not function correctly.

npx servercn add not-found-handler

This 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.

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`);
};
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.

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;
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

  1. Route Matching: Express processes routes in the order they are defined
  2. Catch-All: The Not Found Handler is placed after all defined routes
  3. Error Throwing: When a request doesn't match any route, it reaches the Not Found Handler
  4. Error Propagation: The handler throws an ApiError with a 404 status code
  5. 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

File & Folder Structure

Select a file to view its contents

Installation

npx servercn add not-found-handler