[next.js] 외부 이미지 불러오는 방법

적자생존·2023년 2월 7일
2

next.js

목록 보기
5/6

1. 외부 이미지가 불러와지지 않는 문제점

next.js로 외부의 이미지 즉 프로젝트 내부의 루트에 public 폴더의 이미지들은 아무 문제 없이 잘 불러와졌다.

하지만 내 프로젝트가 아닌 외부에서 이미지를 불러오는 경우에


<Image src={`http://localhost:5000/image/image.png`}/>

리액트처럼 url을 명시하여 코드를 작성하면

Invalid src prop (http://localhost:5000/uploads/images/6c3c94e3-cab9-4823-966c-51d32e93ea4a.png) on next/image, hostname "localhost" is not configured under images in your next.config.js
See more info: https://nextjs.org/docs/messages/next-image-unconfigured-host

라는 메세지를 볼 수 있다.

구글링을 해 본 결과 next.js 13 정확히 Image 컴포넌트를 사용할 때 반드시 next.js의 next.config.js에 외부 경로를 등록을 해 두어야 한다고 명시하고 있었다.

이를 해결하기 위해서 next.config.js를 건드려 본다.

2. next.js의 Image 컴포넌트 사용

import Image from "next/image"


<Image src={/icon/icon.png} alt="테스트"/>

위의 방식으로 사용하면 이미지가 불러와진다.

3. next.config.js에 hostname 등록하러 가기

루트폴더에 next.config.js에 들어가면

초기에 create-next-app을 했을 때 설정되어 있던

/** @type {import('next').NextConfig} */

const nextConfig = {
  reactStrictMode: true,
}
module.exports = nextConfig;

코드가 반길 것이다.

이제 여기서 외부 이미지를 등록할 것이다.

nextConfig.images.remotePatterns를 등록할 것이다.

const nextConfig = {
	reactStrictMode: true,
  	images: {
    remotePatterns: [
      {
        protocol: "http",
        hostname: "localhost",
      },
    ],
  },
}

위와 같이 localhost를 hostname에 등록한다.

추가로 등록을 하고 싶으면

const nextConfig = {
  reactStrictMode: true,
  images: {
    remotePatterns: [
      {
        protocol: "http",
        hostname: "t1.daumcdn.net",
      },
      {
        protocol: "http",
        hostname: "localhost",
      },
    ],
  },
};

위와 같이 작성하면 여러 개를 추가할 수 있다.

docs

https://nextjs.org/docs/messages/next-image-unconfigured-host

참고

https://velog.io/@hhhminme/Next.js%EC%97%90%EC%84%9C-Nextimage%EC%97%90%EC%84%9C-%EC%99%B8%EB%B6%80-%EC%9D%B4%EB%AF%B8%EC%A7%80%EB%A5%BC-%EB%AA%BB%EA%B0%80%EC%A0%B8%EC%98%A4%EB%8A%94-%EB%AC%B8%EC%A0%9C%EB%8F%84%EB%A9%94%EC%9D%B8-%EC%84%A4%EC%A0%95%ED%95%98%EA%B8%B0-loader-%EC%A0%81%EC%9A%A9%ED%95%98%EA%B8%B0

profile
적는 자만이 생존한다.

0개의 댓글