nexus
nexus
is the primary function for server-side data fetching in Server Components. It integrates with Next.js’s data cache and automatically captures fetched data for client-side hydration.
Import
import { nexus } from "next-nexus/server";
Signature
nexus<T>(definition: NexusDefinition<T>): Promise<NexusResponse<T>>
- It takes a
definition
object and returns aPromise
that resolves to{ data, headers }
. - It must be used within a tree wrapped by
NexusHydrationBoundary
or a page exported withwithNexusHydrationBoundary
for hydration to work.
Examples
Basic Fetch
A minimal example in a page component.
// 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>Products ({total ?? "n/a"})</h1>
<ul>
{products?.map((p) => (
<li key={p.id}>{p.name}</li>
))}
</ul>
</div>
);
}
export default withNexusHydrationBoundary(ProductsPage);
Multiple Requests
Use Promise.all
to fetch data from multiple endpoints concurrently.
// app/(shop)/dashboard/page.tsx
import { withNexusHydrationBoundary, nexus } from "next-nexus/server";
import { productDefinition } from "@/api/productDefinition";
import { statsDefinition } from "@/api/statsDefinition"; // Assuming this exists
async function DashboardPage() {
const [productsRes, statsRes] = await Promise.all([
nexus(productDefinition.list),
nexus(statsDefinition.summary),
]);
return (
<div>
<h2>
Stats: users {statsRes.data?.users} / orders {statsRes.data?.orders}
</h2>
<ul>
{productsRes.data?.map((p) => (
<li key={p.id}>{p.name}</li>
))}
</ul>
</div>
);
}
export default withNexusHydrationBoundary(DashboardPage);
Revalidation After Mutations
To revalidate server-cached data after a mutation, use revalidateServerTags
in a Server Action. This is often paired with revalidateClientTags
to update the client UI.
// app/actions.ts
"use server";
import { revalidateServerTags } from "next-nexus";
import { revalidateClientTags } from "next-nexus/client"; // This would be called on the client
export async function updateProduct() {
// ... perform database update
// Revalidate the Next.js cache for server components
await revalidateServerTags(["products"]);
// On the client, you would then call this to update useQuery instances
// revalidateClientTags(['products']);
}
Definition Options
The behavior of nexus
is controlled by the definition
object passed to it. This includes caching, revalidation, timeouts, retries, and more.
For a complete list of options, see the Definitions page.
See also
Last updated on