Next.js에서 Next/image에서 외부 이미지를 못가져오는 문제(도메인 설정하기, loader 적용하기)

허민(허브)·2022년 4월 17일
10

Next.js를 통해 위처럼 개발을 하려고 했었다. json 내 이미지 파일명이 담겨져서 서버 내 리소스 파일에 접근을 해서 가져와야했다.

Next.js Un-configured Host 문제

On one of your pages that leverages the next/image component, you passed a src value that uses a hostname in the URL that isn't defined in the images.domains config in next.config.js.

쉽게 쓰면 우리가 쓰는 Next/image에서는 src에 들어가는 도메인을 미리 next.config.js에 정의를 해줄 필요가 있다. 정적파일의 접근은 상관없지만 나는 외부 서버의 이미지를 가져와야하기 때문에 도메인 설정이 필요했다.

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    domains: ["localhost", "*"],
  },
  reactStrictMode: true,
};

module.exports = nextConfig;

이렇게 images 의 도메인을 설정해주면 되는데 이때 문제는 해당 설정을 가장 상단에 해주지 않으면 인식을 잘 하지 못한다는 문제가 있었다. 그러니 꼭 도메인 설정은 맨 위에 해주어야 한다.
만약 이런 과정을 거치지 않고 직접 src 주소를 넣고 싶으면 loader() 활용하는 방법도 존재한다.

next/image Un-configured Host 참고 주소

그래도 이미지가 안뜨는데요..?

Same issue here, preventing us from upgrading to 10.1.x. Passing unoptimized={true} will allow images to render, but obviously turns off any worthwhile optimizations.

그 이유는 Next.js는 내장 이미지 컴포넌트와 자동 이미지 최적화를 지원하기 때문이다. 그래서 해당 설정을 해주어도 console을 통해 확인해보면 img 의 src가 조금 이상하게 뜰 것이다.

따라서 Next.js를 100% 활용하진 못하지만 아래와 같이 문제를 해결할 수 있다. 아래의 설정에서 unoptimized={true}를 주게 될 경우 최적화가 이루어지지 않는다.

 <Image
              src={`http://localhost:8080/images/${fileName}`}
              alt="음식 사진"
              width="64"
              height="64"
              unoptimized={true}
            />

Signed images from S3 no longer working with next/image 참고

최적화를 거치지 않고 loader를 활용하여 이미지를 띄우는 방법

If you want to use a cloud provider to optimize images instead of using the Next.js built-in Image Optimization API, you can configure the loader and path prefix in your next.config.js file. This allows you to use relative URLs for the Image src and automatically generate the correct absolute URL for your provider.

module.exports = {
  images: {
    loader: 'imgix',
    path: 'https://example.com/myaccount/',
  },
}

이렇게 설정해주면 해당 도메인의 path로 직접 접근하게 되어 이미지를 가져올 수 있다.

profile
Adventure, Challenge, Consistency

0개의 댓글