소개

Next.js Image Component 는 간단하게 이미지 최적화 기능을 사용할 수 있도록 도와준다.

이번에 Vercel을 사용하지 않고 Next.js를 직접 서빙할 일이 생겼다.

Next.js는 Vercel을 사용하지 않아도 sharp 라이브러리 기반으로 고성능의 이미지 최적화를 제공하지만, Next.js 서버에 부담을 줄이고 싶어 Custom Image Loader를 사용하려고 한다.

ImgProxy

ImgProxy는 Golang 기반의 오픈 소스 이미지 최적화 솔루션이다. Docker로 간단하게 서빙할 수 있고, 고성능이다.

다만 별도의 캐시는 없기 때문에 CDN, 캐시 서버를 앞 단에 둬야한다.

Next.js에 적용하기

ImgProxy 블로그에 관련된 내용이 기재되어 있다. RSC를 이용해 Signing URL을 진행할 수도 있지만, 굳이 필요하지 않은 기능이어서 unsafe URL로만 진행했다.

import { type ImageLoaderProps } from "next/image";
import { generateUrl } from "@imgproxy/imgproxy-js-core";
// The address of your imgproxy server
const imgproxyEndpoint = process.env.NEXT_PUBLIC_IMGPROXY_ENDPOINT || "http://localhost:8080";
// The address of your Next.js server.
// This is used to resolve relative image URLs.
const imgproxyBaseUrl = process.env.NEXT_PUBLIC_IMGPROXY_BASE_URL || "http://host.docker.internal:8100";
export default ({ src, width, quality }: ImageLoaderProps) => {
const fullSrc = new URL(src, imgproxyBaseUrl).toString();
const escapedSrc = fullSrc.replace("%", "%25").replace("?", "%3F").replace("@", "%40");
const path = generateUrl(
{ value: escapedSrc, type: "plain" },
{ width, quality },
);
return `${imgproxyEndpoint}/unsafe${path}`;
}

이 코드는 위 블로그 글에서 발췌한 코드인데, 보면 escapedSrc에서 %, ?, @ 이외에는 처리되지 않는 문제가 있다. 나는 이 부분을 encodeURIComponent 를 이용하여 다음과 같이 변경해주었다.

const escapedSrc = encodeURIComponent(fullSrc);

태그
next.js
javascript
imgproxy
반응과 댓글 시스템은 Giscus에 의해 호스팅되며, 모든 대화는 GitHub에 저장됩니다.

출처가 명확하지 않은 내용을 신뢰하지 마세요. 글 작성자는 이로 인해 발생하는 책임을 지지 않습니다.

피드백 무엇이든 환영합니다 🤗

doda.devlicensegithubmade with ☕️

imgproxy로 Next.js Image 사용하기 – 도다위키