프로그래밍 공부방

[Next.js] Error: Invalid src prop (...) on `next/image`, hostname "..." is not configured under images in your `next.config.js` 본문

프론트엔드/Next.js

[Next.js] Error: Invalid src prop (...) on `next/image`, hostname "..." is not configured under images in your `next.config.js`

김갱갱 2023. 6. 29. 23:48

🔥에러 내용: Error: Invalid src prop (...) on `next/image`, hostname "..." is not configured under images in your `next.config.js`

Nextjs의 Image를 사용하려는데 오류가 발생했습니다.

🤷‍♀️Why?🤷‍♀️

원격 이미지를 가져오기 위해서는 이미지를 가져올 도메인을 추가해주어야 하는데,
해당 작업을 안해줬기 때문에 AWS 호스트 허용이 되지 않아서 발생한 오류입니다.

✨해결 방법

next.config.js에 다음과 같이 추가해줍니다.

 

1. Next.js 12.3.0 이후 버전을 사용 중인 경우

// next.config.js

module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'assets.example.com',
        port: '',
        pathname: '/account123/**',
      },
    ],
  },
}

2. Next.js 12.3.0 이전 버전을 사용 중인 경우

// next.config.js

module.exports = {
  images: {
    domains: ['assets.example.com'],
  },
}

출처 :  next-image-unconfigured-host | Next.js (nextjs.org)

 

next-image-unconfigured-host | Next.js

next/image Un-configured Host One of your pages that leverages the next/image component, passed a src value that uses a hostname in the URL that isn't defined in the images.remotePatterns in next.config.js. Add the protocol, hostname, port, and pathname to

nextjs.org

 

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
};

module.exports = {
  images: {
    domains: [
      "~~~.amazonaws.com",
      "~~~.cloudflarestream.com",
    ],
  },
};

module.exports = nextConfig;

하지만 저는 위 방법처럼 이미 aws 도메인을 추가해준 상태인데도 불구하고 오류가 발생한 경우였습니다ㅠㅠ 

 

 

이 때 Image에 unoptimized={true}를 넣어주면 오류가 해결됩니다.

하지만 unoptimized를 넣어주면 Nextjs에서 제공하는 이미지 최적화 기능을 사용할 수 없게 됩니다.

<Image unoptimized={true} src={image} width={80} height={80}/>

 

다른 방법으로는 Image에 loader를 추가해주는 방법이 있습니다.

<Image
    priority={true}
    loader={() => {
      return image + "?w=80";
    }}
    src={image}
    width={80}
    height={80}
/>

loader는 이미지의 URL을 생성하는 기능입니다.

loader 기본 설정을 그대로 두고 src에 대한 절대 URL을 입력하면 Next.js 이미지 최적화 API를 사용할 수 있습니다. 

 

https://nextjs.org/docs/pages/building-your-application/optimizing/images#remote-images

 

Optimizing: Images | Next.js

Using Pages Router Features available in /pages

nextjs.org