View as Json

Validate ObjectId Middleware

Middleware to validate MongoDB ObjectId parameters in Express routes.

Installation Guide

Install the component using the servercn CLI:

npx servercn-cli@latest 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

......

Installation

npx servercn-cli@latest add validate-objectid

Contributed by