使用Next.js Image组件时遭遇必填src属性缺失错误的求助
Let's break down why you're hitting this error and how to fix it quickly:
The Root Cause
Even though you're passing a valid Cloudinary URL when coverImage exists, Next.js's Image component throws this error when the src prop is undefined. This happens because:
- On initial render (before your
coverImagedata loads, maybe from an API),coverImageis likelyundefined - Using optional chaining (
coverImage?.sourceUrl) returnsundefinedwhen the parent value is missing, which isn't acceptable to theImagecomponent (unlike the native<img>tag, which just ignores an undefinedsrc)
Step-by-Step Fix
Add conditional rendering for the Image component
Update yourimagevariable to only render theImagewhencoverImage?.sourceUrlexists. You can also add a fallback placeholder for loading states:const image = coverImage?.sourceUrl ? ( <Image src={coverImage.sourceUrl} height={coverImage.mediaDetails.height} width={coverImage.mediaDetails.width} className={cn("shadow-small", { "hover:shadow-medium transition-shadow duration-200": slug })} alt={title} // Don't forget this for accessibility! /> ) : ( // Fallback for when image data isn't ready <div className="shadow-small bg-gray-100 h-full w-full flex items-center justify-center"> <span className="text-gray-500">Loading cover image...</span> </div> );Verify your data loading flow
Check theconsole.log(coverImage)output in your browser dev tools:- You'll probably see
undefinedlogged on the first render, then the actualcoverImageobject once your data loads - If this is the case, the conditional render above will prevent the
Imagecomponent from mounting until the data is ready, eliminating the error
- You'll probably see
Double-check your Next.js config (already good!)
Yournext.config.jscorrectly includesres.cloudinary.cominimages.domains, which is why the native<img>tag works. No changes needed here.
Bonus Best Practice
Always include an alt prop on your Image components—it's required for accessibility and helps with SEO. Using the title prop value is a perfect fit for a cover image.
That's it! This should resolve the missing src error while keeping your image loading behavior intact.
内容的提问来源于stack exchange,提问作者michaelward82




