You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

使用Next.js Image组件时遭遇必填src属性缺失错误的求助

Fix: Next.js Image Component Missing Required "src" Property

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 coverImage data loads, maybe from an API), coverImage is likely undefined
  • Using optional chaining (coverImage?.sourceUrl) returns undefined when the parent value is missing, which isn't acceptable to the Image component (unlike the native <img> tag, which just ignores an undefined src)

Step-by-Step Fix

  1. Add conditional rendering for the Image component
    Update your image variable to only render the Image when coverImage?.sourceUrl exists. 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>
    );
    
  2. Verify your data loading flow
    Check the console.log(coverImage) output in your browser dev tools:

    • You'll probably see undefined logged on the first render, then the actual coverImage object once your data loads
    • If this is the case, the conditional render above will prevent the Image component from mounting until the data is ready, eliminating the error
  3. Double-check your Next.js config (already good!)
    Your next.config.js correctly includes res.cloudinary.com in images.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

火山引擎 最新活动