nextjs-server-components
Use when next.js Server Components for optimal performance. Use when building data-intensive Next.js applications.
What this skill does
# Next.js Server Components
Master Server Components in Next.js to build high-performance
applications with server-side rendering and data fetching.
## Server Components Basics
In Next.js App Router, all components are Server Components by default:
```typescript
// app/posts/page.tsx (Server Component by default)
async function getPosts() {
const res = await fetch('https://api.example.com/posts', {
next: { revalidate: 3600 } // Cache for 1 hour
});
if (!res.ok) throw new Error('Failed to fetch posts');
return res.json();
}
export default async function Posts() {
const posts = await getPosts();
return (
<div>
<h1>Blog Posts</h1>
{posts.map((post: Post) => (
<article key={post.id}>
<h2>{post.title}</h2>
<p>{post.content}</p>
<span>{new Date(post.date).toLocaleDateString()}</span>
</article>
))}
</div>
);
}
// Direct database access (server-only)
import { db } from '@/lib/db';
export default async function Users() {
const users = await db.user.findMany({
select: {
id: true,
name: true,
email: true
}
});
return (
<div>
{users.map(user => (
<div key={user.id}>
{user.name} - {user.email}
</div>
))}
</div>
);
}
```
## Server vs Client Components Decision Tree
```typescript
// Use Server Components when:
// - Fetching data
// - Accessing backend resources directly
// - Keeping sensitive information on server
// - Keeping large dependencies on server
// Server Component (default)
export default async function ServerComp() {
const data = await fetchData();
return <div>{data}</div>;
}
// Use Client Components when:
// - Using interactivity (onClick, onChange, etc.)
// - Using state or lifecycle hooks (useState, useEffect)
// - Using browser-only APIs (localStorage, window, etc.)
// - Using custom hooks that depend on state/effects
// - Using React Context
// Client Component
'use client';
import { useState } from 'react';
export default function ClientComp() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
// Composition: Server Component with Client Component
export default async function Page() {
const data = await fetchData(); // Server-side
return (
<div>
<ServerContent data={data} />
<InteractiveButton /> {/* Client Component */}
</div>
);
}
```
## Server Actions for Mutations
```typescript
// app/actions.ts - Server Actions
'use server';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
export async function createPost(formData: FormData) {
const title = formData.get('title') as string;
const content = formData.get('content') as string;
const post = await db.post.create({
data: { title, content }
});
revalidatePath('/posts');
redirect(`/posts/${post.id}`);
}
export async function updatePost(id: string, formData: FormData) {
const title = formData.get('title') as string;
const content = formData.get('content') as string;
await db.post.update({
where: { id },
data: { title, content }
});
revalidatePath(`/posts/${id}`);
return { success: true };
}
export async function deletePost(id: string) {
await db.post.delete({ where: { id } });
revalidatePath('/posts');
}
// app/posts/new/page.tsx - Using Server Actions
export default function NewPost() {
return (
<form action={createPost}>
<input name="title" placeholder="Title" required />
<textarea name="content" placeholder="Content" required />
<button type="submit">Create Post</button>
</form>
);
}
// With client-side enhancement
'use client';
import { useFormStatus, useFormState } from 'react-dom';
import { createPost } from './actions';
function SubmitButton() {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? 'Creating...' : 'Create Post'}
</button>
);
}
export default function NewPostForm() {
const [state, formAction] = useFormState(createPost, null);
return (
<form action={formAction}>
<input name="title" required />
<textarea name="content" required />
{state?.error && <p className="error">{state.error}</p>}
<SubmitButton />
</form>
);
}
```
## Data Fetching Patterns
```typescript
// Parallel data fetching
async function getUser(id: string) {
const res = await fetch(`/api/users/${id}`);
return res.json();
}
async function getUserPosts(id: string) {
const res = await fetch(`/api/users/${id}/posts`);
return res.json();
}
export default async function UserProfile({ params }: {
params: { id: string }
}) {
// Fetch in parallel
const [user, posts] = await Promise.all([
getUser(params.id),
getUserPosts(params.id)
]);
return (
<div>
<UserInfo user={user} />
<UserPosts posts={posts} />
</div>
);
}
// Sequential data fetching (when needed)
export default async function Dashboard() {
// Fetch user first
const user = await getUser();
// Then fetch user-specific data
const settings = await getUserSettings(user.id);
const notifications = await getUserNotifications(user.id);
return (
<div>
<UserHeader user={user} settings={settings} />
<Notifications items={notifications} />
</div>
);
}
// Waterfall optimization with Suspense
import { Suspense } from 'react';
export default function Page() {
return (
<div>
{/* User loads first */}
<Suspense fallback={<UserSkeleton />}>
<User />
</Suspense>
{/* These load in parallel */}
<div className="grid">
<Suspense fallback={<SettingsSkeleton />}>
<Settings />
</Suspense>
<Suspense fallback={<NotificationsSkeleton />}>
<Notifications />
</Suspense>
</div>
</div>
);
}
```
## Streaming with Suspense
```typescript
// app/dashboard/page.tsx
import { Suspense } from 'react';
export default function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
{/* Fast component renders immediately */}
<QuickStats />
{/* Slow components stream in */}
<Suspense fallback={<ChartSkeleton />}>
<RevenueChart />
</Suspense>
<Suspense fallback={<TableSkeleton />}>
<RecentOrders />
</Suspense>
<Suspense fallback={<ActivitySkeleton />}>
<ActivityFeed />
</Suspense>
</div>
);
}
async function RevenueChart() {
// Slow data fetch
const data = await fetchRevenueData();
return <Chart data={data} />;
}
async function RecentOrders() {
const orders = await fetchOrders({ limit: 10 });
return (
<table>
{orders.map(order => (
<tr key={order.id}>
<td>{order.id}</td>
<td>{order.total}</td>
</tr>
))}
</table>
);
}
// Nested Suspense for granular streaming
async function ActivityFeed() {
return (
<div>
<h2>Activity</h2>
<Suspense fallback={<div>Loading comments...</div>}>
<Comments />
</Suspense>
<Suspense fallback={<div>Loading likes...</div>}>
<Likes />
</Suspense>
</div>
);
}
```
## Server Component Patterns
```typescript
// Pattern 1: Data fetching in Server Component
async function fetchProduct(id: string) {
const product = await db.product.findUnique({ where: { id } });
return product;
}
export default async function ProductPage({ params }: {
params: { id: string }
}) {
const product = await fetchProduct(params.id);
return (
<div>
<ProductDetails product={product} />
<AddToCartButton productId={product.id} /> {/* Client Component */}
</div>
);
}
// Pattern 2: Server Component as data provider
async function ProductWithReviews({ id }: { id: string }) {
const [product, reviews] = await Promise.all([
fetchProduct(id)Related in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.