Next.js에서 fetch
함수는 데이터를 클라이언트나 서버에서 가져오기 위해 사용됩니다. Next.js는 React 기반의 프레임워크로, 서버사이드 렌더링(SSR)과 정적 사이트 생성(SSG)을 지원합니다. 이 특성에 따라 fetch
는 클라이언트와 서버 양쪽에서 사용할 수 있지만, 각 환경에서 동작 방식이 다릅니다.
클라이언트에서는 브라우저의 기본 fetch
API를 활용하여 데이터를 가져옵니다. 이는 React 컴포넌트의 useEffect
나 이벤트 핸들러 내부에서 자주 사용됩ㄴ다.
import { useEffect, useState } from 'react';
export default function ClientFetch() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('/...') // api url
.then((res) => res.json())
.then((data) => setData(data));
}, []);
return <div>{data ? JSON.stringify(data) : 'Loading...'}</div>
Next.js의 서버 환경에서는 Node.js의 네이티브 환경에서 fetch
가 동작합니다. 서버 컴포넌트나 API 라우트에서 사용할 수 있으며, 특히 SSR 및 SSG에서 많이 활용됩니다.
export async function getServerSideProps() {
const res await fetch('...');
const data = await res.json();
return { props: { data } };
}
export default function ServerFetch ({ data }) {
return <div>{JSON.stringify(data)}</div>;
}
/api
경로를 통해 클라이언트와 서버 간 데이터를 주고받습니다.export async function getStaticProps() {
const res = await fetch('/...');
const data = await res.json();
return { props: { data } };
}
export default function StaticPage({data}) {
return <div>{JSON.stringify(data)}</div>;
}
fetch
를 사용하는 위치가 클라이언트인지 서버인지에 따라 API 호출 방식과 효율성이 달라집니다.try {
const res = await fetch('/...');
if(!res.ok) throw new Error('Error Message');
const data = await res.json();
} catch(error) {
console.error('Fetch Error: ', error);
}
fetch
를 사용할 수 있으며 각 환경에 따라 데이터 가여오기 방식이 다릅니다. getServerSideProps
와 getStaticProps
를 통해 SSR/SSG에서 fetch
를 쉽게 통합할 수 있습니다.API Routes
를 사용하면 데이터를 보다 안전하고 효율적으로 관리할 수 있습니다.