nexus
nexus
는 서버 컴포넌트에서 데이터를 가져오기 위한 핵심 함수입니다. Next.js의 데이터 캐시와 통합되어 동작하며, 가져온 데이터를 클라이언트 하이드레이션을 위해 자동으로 수집합니다.
Import
import { nexus } from 'next-nexus/server';
시그니처 (Signature)
nexus<T>(definition: NexusDefinition<T>): Promise<NexusResponse<T>>
definition
객체를 인자로 받아,{ data, headers }
를 포함하는Promise
를 반환합니다.- 하이드레이션이 동작하려면 반드시
NexusHydrationBoundary
로 감싸진 트리 또는withNexusHydrationBoundary
로 export된 페이지 내에서 사용해야 합니다.
예제 (Examples)
기본 페칭
페이지 컴포넌트에서의 최소 사용 예제입니다.
// app/(shop)/products/page.tsx
import { withNexusHydrationBoundary, nexus } from 'next-nexus/server';
import { productDefinition } from '@/api/productDefinition';
async function ProductsPage() {
const { data: products, headers } = await nexus(productDefinition.list);
const total = headers.get('x-total-count');
return (
<div>
<h1>상품 목록 ({total ?? 'n/a'})</h1>
<ul>{products?.map(p => <li key={p.id}>{p.name}</li>)}</ul>
</div>
);
}
export default withNexusHydrationBoundary(ProductsPage);
다중 요청
Promise.all
을 사용하여 여러 엔드포인트의 데이터를 병렬로 가져올 수 있습니다.
// app/(shop)/dashboard/page.tsx
import { withNexusHydrationBoundary, nexus } from 'next-nexus/server';
import { productDefinition } from '@/api/productDefinition';
import { statsDefinition } from '@/api/statsDefinition'; // statsDefinition이 있다고 가정
async function DashboardPage() {
const [productsRes, statsRes] = await Promise.all([
nexus(productDefinition.list),
nexus(statsDefinition.summary),
]);
return (
<div>
<h2>통계: 사용자 {statsRes.data?.users}명 / 주문 {statsRes.data?.orders}건</h2>
<ul>{productsRes.data?.map(p => <li key={p.id}>{p.name}</li>)}</ul>
</div>
);
}
export default withNexusHydrationBoundary(DashboardPage);
Mutation 이후 재검증
Mutation 이후 서버 캐시 데이터를 재검증하려면, 서버 액션 내에서 revalidateServerTags
를 사용합니다. 보통 클라이언트 UI를 업데이트하기 위해 revalidateClientTags
와 함께 사용됩니다.
// app/actions.ts
'use server'
import { revalidateServerTags } from 'next-nexus'
import { revalidateClientTags } from 'next-nexus/client' // 클라이언트에서 호출됨
export async function updateProduct() {
// ... 데이터베이스 업데이트 수행
// 서버 컴포넌트를 위한 Next.js 캐시 재검증
await revalidateServerTags(['products']);
// 이후 클라이언트에서 useQuery 인스턴스를 업데이트하기 위해 호출
// revalidateClientTags(['products']);
}
Definition Options
nexus
의 동작은 전달되는 definition
객체에 의해 제어됩니다. 여기에는 캐싱, 재검증, 타임아웃, 재시도 등이 포함됩니다.
전체 옵션 목록은 Definitions 페이지를 참고하세요.
함께 보기
Last updated on