Advanced Server Components patterns with streaming, suspense boundaries, and data fetching strategies
# Next.js Server Components for Google Antigravity
Master React Server Components in Next.js with Google Antigravity's Gemini 3 engine. This guide covers streaming, suspense boundaries, server actions, and optimal data fetching patterns.
## Server Component Data Fetching
```typescript
// app/products/page.tsx
import { Suspense } from 'react';
import { ProductList } from './ProductList';
import { ProductFilters } from './ProductFilters';
import { ProductListSkeleton } from './ProductListSkeleton';
interface SearchParams {
category?: string;
search?: string;
page?: string;
}
export default async function ProductsPage({
searchParams,
}: {
searchParams: SearchParams;
}) {
// searchParams are available in Server Components
const filters = {
category: searchParams.category,
search: searchParams.search,
page: parseInt(searchParams.page || '1'),
};
return (
<div className="container py-8">
<h1 className="text-3xl font-bold mb-8">Products</h1>
{/* Client Component for interactivity */}
<ProductFilters initialFilters={filters} />
{/* Suspense boundary for streaming */}
<Suspense
key={JSON.stringify(filters)}
fallback={<ProductListSkeleton />}
>
<ProductList filters={filters} />
</Suspense>
</div>
);
}
// app/products/ProductList.tsx
import { getProducts } from '@/lib/products';
import { ProductCard } from '@/components/ProductCard';
import { Pagination } from '@/components/Pagination';
interface ProductListProps {
filters: {
category?: string;
search?: string;
page: number;
};
}
export async function ProductList({ filters }: ProductListProps) {
// This fetch happens on the server
const { products, pagination } = await getProducts(filters);
if (products.length === 0) {
return (
<div className="text-center py-12">
<p className="text-gray-500">No products found</p>
</div>
);
}
return (
<>
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
{products.map((product) => (
<ProductCard key={product.id} product={product} />
))}
</div>
<Pagination {...pagination} />
</>
);
}
```
## Parallel Data Fetching
```typescript
// app/dashboard/page.tsx
import { Suspense } from 'react';
import { RecentOrders } from './RecentOrders';
import { Analytics } from './Analytics';
import { Notifications } from './Notifications';
import { CardSkeleton } from '@/components/Skeletons';
export default function DashboardPage() {
return (
<div className="container py-8">
<h1 className="text-3xl font-bold mb-8">Dashboard</h1>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Each Suspense boundary streams independently */}
<Suspense fallback={<CardSkeleton />}>
<Analytics />
</Suspense>
<Suspense fallback={<CardSkeleton />}>
<RecentOrders />
</Suspense>
<Suspense fallback={<CardSkeleton />}>
<Notifications />
</Suspense>
</div>
</div>
);
}
// Parallel fetching in a single component
// app/dashboard/Analytics.tsx
import { getRevenue, getOrders, getCustomers } from '@/lib/analytics';
export async function Analytics() {
// Fetch all data in parallel
const [revenue, orders, customers] = await Promise.all([
getRevenue(),
getOrders(),
getCustomers(),
]);
return (
<div className="bg-white rounded-lg p-6 shadow">
<h2 className="text-xl font-semibold mb-4">Analytics</h2>
<div className="space-y-4">
<Stat label="Revenue" value={`$${revenue.toLocaleString()}`} />
<Stat label="Orders" value={orders.toString()} />
<Stat label="Customers" value={customers.toString()} />
</div>
</div>
);
}
```
## Server Actions
```typescript
// app/products/actions.ts
'use server';
import { revalidatePath, revalidateTag } from 'next/cache';
import { redirect } from 'next/navigation';
import { z } from 'zod';
import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
const ProductSchema = z.object({
name: z.string().min(1).max(100),
description: z.string().max(1000),
price: z.coerce.number().positive(),
categoryId: z.string().uuid(),
});
export async function createProduct(formData: FormData) {
const session = await auth();
if (!session?.user) {
throw new Error('Unauthorized');
}
const validatedFields = ProductSchema.safeParse({
name: formData.get('name'),
description: formData.get('description'),
price: formData.get('price'),
categoryId: formData.get('categoryId'),
});
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
};
}
const product = await db.product.create({
data: {
...validatedFields.data,
userId: session.user.id,
},
});
revalidateTag('products');
redirect(`/products/${product.id}`);
}
export async function updateProduct(id: string, formData: FormData) {
const session = await auth();
if (!session?.user) {
throw new Error('Unauthorized');
}
const validatedFields = ProductSchema.safeParse({
name: formData.get('name'),
description: formData.get('description'),
price: formData.get('price'),
categoryId: formData.get('categoryId'),
});
if (!validatedFields.success) {
return { errors: validatedFields.error.flatten().fieldErrors };
}
await db.product.update({
where: { id, userId: session.user.id },
data: validatedFields.data,
});
revalidatePath(`/products/${id}`);
return { success: true };
}
export async function deleteProduct(id: string) {
const session = await auth();
if (!session?.user) {
throw new Error('Unauthorized');
}
await db.product.delete({
where: { id, userId: session.user.id },
});
revalidateTag('products');
redirect('/products');
}
```
## Form with Server Action
```typescript
// app/products/new/page.tsx
import { createProduct } from '../actions';
import { SubmitButton } from '@/components/SubmitButton';
export default function NewProductPage() {
return (
<div className="container max-w-2xl py-8">
<h1 className="text-3xl font-bold mb-8">New Product</h1>
<form action={createProduct} className="space-y-6">
<div>
<label htmlFor="name" className="block text-sm font-medium">
Name
</label>
<input
type="text"
id="name"
name="name"
required
className="mt-1 block w-full rounded-md border px-3 py-2"
/>
</div>
<div>
<label htmlFor="price" className="block text-sm font-medium">
Price
</label>
<input
type="number"
id="price"
name="price"
step="0.01"
min="0"
required
className="mt-1 block w-full rounded-md border px-3 py-2"
/>
</div>
<div>
<label htmlFor="description" className="block text-sm font-medium">
Description
</label>
<textarea
id="description"
name="description"
rows={4}
className="mt-1 block w-full rounded-md border px-3 py-2"
/>
</div>
<SubmitButton>Create Product</SubmitButton>
</form>
</div>
);
}
// components/SubmitButton.tsx
'use client';
import { useFormStatus } from 'react-dom';
export function SubmitButton({ children }: { children: React.ReactNode }) {
const { pending } = useFormStatus();
return (
<button
type="submit"
disabled={pending}
className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 disabled:opacity-50"
>
{pending ? 'Submitting...' : children}
</button>
);
}
```
## Best Practices
Google Antigravity's Gemini 3 engine recommends these Server Component patterns: Use Suspense boundaries for progressive loading. Fetch data in parallel when possible. Keep client components minimal and leaf-level. Use Server Actions for form submissions. Implement proper error boundaries for resilient UIs.This Next.js prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their next.js implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Next.js projects, consider mentioning your framework version, coding style, and any specific libraries you're using.