nextjs config_error ai_generated true

Error: Invalid src prop on `next/image`, src must be a string and cannot be a relative path.

ID: nextjs/invalid-image-src-relative-path

Also available as: JSON · Markdown · 中文
95%Fix Rate
90%Confidence
1Evidence
2023-09-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
Next.js 13.0 active
Next.js 14.0 active
Next.js 14.2 active
Next.js 15.0 active

Root Cause

The `src` prop on the `next/image` component is a relative path (e.g., './image.png' or '../assets/img.jpg') instead of an absolute URL or a static import. Next.js requires either an absolute URL (for remote images) or a static import (for local images).

generic

中文

`next/image` 组件上的 `src` 属性是相对路径(例如 './image.png' 或 '../assets/img.jpg'),而不是绝对 URL 或静态导入。Next.js 要求对于远程图像使用绝对 URL,对于本地图像使用静态导入。

Official Documentation

https://nextjs.org/docs/app/api-reference/components/image

Workarounds

  1. 95% success Use a static import for local images: import logo from './logo.png' and pass it as src.
    Use a static import for local images: import logo from './logo.png' and pass it as src.
  2. 90% success Use an absolute URL for remote images. Ensure the hostname is configured in next.config.js under images.remotePatterns.
    Use an absolute URL for remote images. Ensure the hostname is configured in next.config.js under images.remotePatterns.
  3. 85% success Place the image in the 'public' directory (e.g., 'public/images/logo.png') and reference it with an absolute path from the root: '/images/logo.png'. This works because public files are served as static assets.
    Place the image in the 'public' directory (e.g., 'public/images/logo.png') and reference it with an absolute path from the root: '/images/logo.png'. This works because public files are served as static assets.

中文步骤

  1. 对本地图像使用静态导入:import logo from './logo.png' 并将其作为 src 传递。
  2. 对远程图像使用绝对 URL。确保主机名在 next.config.js 的 images.remotePatterns 下配置。
  3. 将图像放在 'public' 目录中(例如 'public/images/logo.png'),并使用来自根目录的绝对路径引用:'/images/logo.png'。这是因为公共文件作为静态资源提供。

Dead Ends

Common approaches that don't work:

  1. 80% fail

    A leading slash is still a relative path from the domain root, not an absolute URL. Next.js does not treat it as a valid local image path unless it is a static import.

  2. 70% fail

    Data URLs are strings but are not supported by `next/image` for optimization. The error may change to 'Invalid src prop' or 'Image optimization failed'.

  3. 60% fail

    The loader prop customizes the image URL generation but does not change the requirement that src must be an absolute URL or static import. The validation still fails.