View as Json

Validate ObjectId Middleware

The Validate ObjectId Middleware ensures that route parameters intended to be MongoDB ObjectIds are valid before the request reaches your controller. This prevents CastError exceptions from Mongoose and ensures strictly typed ID handling.


Installation Guide

Install the component using the servercn CLI:

npx servercn-cli add validate-objectid

Basic Implementation

src/middlewares/validate-id.ts
import { Request, Response, NextFunction } from "express";
import { isValidObjectId } from "mongoose";
import { ApiError } from "../utils/api-error";
 
/**
 * Middleware to validate MongoDB ObjectId
 * @param paramName - The name of the parameter to validate (default: "id")
 */
export const validateObjectId = (paramName: string = "id") => {
  return (req: Request, res: Response, next: NextFunction) => {
    const value =
      req.params[paramName] || req.body[paramName] || req.query[paramName];
    if (!value) {
      throw ApiError.badRequest(`${paramName} is required`);
    }
 
    if (!isValidObjectId(value)) {
      throw ApiError.badRequest(`Invalid ${paramName}`);
    }
 
    next();
  };
};

Usage Example

Apply the middleware to any route that contains an :id parameter.

import { Router } from "express";
import { validateObjectId } from "../middlewares/validate-id";
import { getUserById, deleteUser } from "../controllers/user.controller";
 
const router = Router();
 
// Validates 'id' param by default
router.get("/:id", validateObjectId(), getUserById);
 
// Validates custom param name 'userId'
router.delete("/:userId", validateObjectId("userId"), deleteUser);
 
export default router;

File & Folder Structure

Loading files...

Installation

npx servercn-cli add validate-objectid