fix(next/image): improve and simplify detect-content-type #82118
🕶️ LGTM
Vade found zero problems... this time.
I've thoroughly reviewed this comprehensive update to Next.js's image optimizer that adds support for new image formats (JXL, HEIC, JP2) while improving content detection robustness.
What Was Reviewed
Main Changes:
- Enhanced format support: Added detection and handling for JPEG XL (JXL), HEIC, and JPEG 2000 (JP2) image formats
- Improved content detection: Converted
detectContentType
from sync to async to leverage Sharp's metadata detection as fallback - Better validation flow: Restructured image type validation to be more explicit and provide clearer error messages
- Test coverage: Added comprehensive test cases for new formats and edge cases (like SVG with leading whitespace)
Technical Implementation:
- Added proper magic number detection patterns for new formats
- Updated BYPASS_TYPES to include JXL and HEIC (appropriate since they're already optimized modern formats)
- Enhanced SVG detection to handle files starting with whitespace by falling back to Sharp
- Properly registered MIME types for new formats in the static file server
- PDF detection added but correctly rejected as non-image content
Verification Performed
I verified the async conversion was handled correctly across all call sites, confirmed the magic number patterns align with format specifications, checked that the Sharp fallback properly handles edge cases, and ensured test coverage validates both successful detection and appropriate rejection of non-image formats.
The restructured validation logic is actually an improvement - it validates image types earlier and provides more specific error messages. All changes demonstrate careful attention to maintaining backward compatibility while extending functionality.
This is a well-architected feature addition that enhances Next.js's image optimization capabilities with modern format support.