Zod schema for validating URL parameters
Express middleware function that validates URL parameters
// Validate UUID parameters for resource endpoints
const uuidParamSchema = z.object({
id: z.string().uuid('Invalid resource ID format')
});
router.get('/users/:id', validateParams(uuidParamSchema), userController.getById);
router.put('/courses/:id', validateParams(uuidParamSchema), courseController.update);
router.delete('/lessons/:id', validateParams(uuidParamSchema), lessonController.delete);
// Multiple parameter validation
const nestedParamSchema = z.object({
courseId: z.string().uuid('Invalid course ID'),
moduleId: z.string().uuid('Invalid module ID'),
lessonId: z.string().uuid('Invalid lesson ID')
});
router.get('/courses/:courseId/modules/:moduleId/lessons/:lessonId',
validateParams(nestedParamSchema),
lessonController.getLesson
);
// Slug-based parameter validation
const slugParamSchema = z.object({
slug: z.string().regex(/^[a-z0-9-]+$/, 'Invalid slug format').min(1).max(100)
});
router.get('/courses/slug/:slug', validateParams(slugParamSchema), courseController.getBySlug);
// Mixed parameter types with transformations
const mixedParamSchema = z.object({
userId: z.string().uuid('Invalid user ID'),
page: z.string().transform(val => parseInt(val, 10)).pipe(z.number().int().min(1)),
category: z.string().min(1).max(50)
});
router.get('/users/:userId/courses/:category/page/:page',
validateParams(mixedParamSchema),
courseController.getUserCoursesByCategory
);
Convenience middleware factory for URL parameter validation only
Creates Express middleware that validates only URL parameters (route parameters) against a Zod schema, ignoring request body and query strings. This function is essential for validating resource identifiers, slugs, and other path-based parameters that determine which resources an API endpoint should operate on.
URL parameters are typically used for resource identification (e.g., user IDs, course IDs) and must be validated to ensure they conform to expected formats (UUIDs, integers, slugs). This validation prevents invalid identifiers from reaching business logic and helps prevent injection attacks through malformed URLs.
The middleware is particularly important for RESTful API endpoints that follow resource-based URL patterns, where parameters directly map to database queries or resource lookups. Proper validation ensures that only well-formed identifiers are processed, improving both security and error handling.