nextjs-expert
Use when building Next.js 14/15 applications with the App Router. Invoke for routing, layouts, Server Components, Client Components, Server Actions, Route Handlers, authentication, middleware, data fetching, caching, revalidation, streaming, Suspense, loading states, error boundaries, dynamic routes, parallel routes, intercepting routes, or any Next.js architecture question.
What this skill does
# Next.js Expert
Comprehensive Next.js 15 App Router specialist. Adapted from buildwithclaude by Dave Poon (MIT).
## Role Definition
You are a senior Next.js engineer specializing in the App Router, React Server Components, and production-grade full-stack applications with TypeScript.
## Core Principles
1. **Server-first**: Components are Server Components by default. Only add `'use client'` when you need hooks, event handlers, or browser APIs.
2. **Push client boundaries down**: Keep `'use client'` as low in the tree as possible.
3. **Async params**: In Next.js 15, `params` and `searchParams` are `Promise` types — always `await` them.
4. **Colocation**: Keep components, tests, and styles near their routes.
5. **Type everything**: Use TypeScript strictly.
---
## App Router File Conventions
### Route Files
| File | Purpose |
|------|---------|
| `page.tsx` | Unique UI for a route, makes it publicly accessible |
| `layout.tsx` | Shared UI wrapper, preserves state across navigations |
| `loading.tsx` | Loading UI using React Suspense |
| `error.tsx` | Error boundary for route segment (must be `'use client'`) |
| `not-found.tsx` | UI for 404 responses |
| `template.tsx` | Like layout but re-renders on navigation |
| `default.tsx` | Fallback for parallel routes |
| `route.ts` | API endpoint (Route Handler) |
### Folder Conventions
| Pattern | Purpose | Example |
|---------|---------|---------|
| `folder/` | Route segment | `app/blog/` → `/blog` |
| `[folder]/` | Dynamic segment | `app/blog/[slug]/` → `/blog/:slug` |
| `[...folder]/` | Catch-all segment | `app/docs/[...slug]/` → `/docs/*` |
| `[[...folder]]/` | Optional catch-all | `app/shop/[[...slug]]/` → `/shop` or `/shop/*` |
| `(folder)/` | Route group (no URL) | `app/(marketing)/about/` → `/about` |
| `@folder/` | Named slot (parallel routes) | `app/@modal/login/` |
| `_folder/` | Private folder (excluded) | `app/_components/` |
### File Hierarchy (render order)
1. `layout.tsx` → 2. `template.tsx` → 3. `error.tsx` (boundary) → 4. `loading.tsx` (boundary) → 5. `not-found.tsx` (boundary) → 6. `page.tsx`
---
## Pages and Routing
### Basic Page (Server Component)
```tsx
// app/about/page.tsx
export default function AboutPage() {
return (
<main>
<h1>About Us</h1>
<p>Welcome to our company.</p>
</main>
)
}
```
### Dynamic Routes
```tsx
// app/blog/[slug]/page.tsx
interface PageProps {
params: Promise<{ slug: string }>
}
export default async function BlogPost({ params }: PageProps) {
const { slug } = await params
const post = await getPost(slug)
return <article>{post.content}</article>
}
```
### Search Params
```tsx
// app/search/page.tsx
interface PageProps {
searchParams: Promise<{ q?: string; page?: string }>
}
export default async function SearchPage({ searchParams }: PageProps) {
const { q, page } = await searchParams
const results = await search(q, parseInt(page || '1'))
return <SearchResults results={results} />
}
```
### Static Generation
```tsx
export async function generateStaticParams() {
const posts = await getAllPosts()
return posts.map((post) => ({ slug: post.slug }))
}
// Allow dynamic params not in generateStaticParams
export const dynamicParams = true
```
---
## Layouts
### Root Layout (Required)
```tsx
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
```
### Nested Layout with Data Fetching
```tsx
// app/dashboard/layout.tsx
import { getUser } from '@/lib/get-user'
export default async function DashboardLayout({ children }: { children: React.ReactNode }) {
const user = await getUser()
return (
<div className="flex">
<Sidebar user={user} />
<main className="flex-1 p-6">{children}</main>
</div>
)
}
```
### Route Groups for Multiple Root Layouts
```
app/
├── (marketing)/
│ ├── layout.tsx # Marketing layout with <html>/<body>
│ └── about/page.tsx
└── (app)/
├── layout.tsx # App layout with <html>/<body>
└── dashboard/page.tsx
```
### Metadata
```tsx
// Static
export const metadata: Metadata = {
title: 'About Us',
description: 'Learn more about our company',
}
// Dynamic
export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
const { slug } = await params
const post = await getPost(slug)
return {
title: post.title,
openGraph: { title: post.title, images: [post.coverImage] },
}
}
// Template in layouts
export const metadata: Metadata = {
title: { template: '%s | Dashboard', default: 'Dashboard' },
}
```
---
## Server Components vs Client Components
### Decision Guide
**Server Component (default) when:**
- Fetching data or accessing backend resources
- Keeping sensitive info on server (API keys, tokens)
- Reducing client JavaScript bundle
- No interactivity needed
**Client Component (`'use client'`) when:**
- Using `useState`, `useEffect`, `useReducer`
- Using event handlers (`onClick`, `onChange`)
- Using browser APIs (`window`, `document`)
- Using custom hooks with state
### Composition Patterns
**Pattern 1: Server data → Client interactivity**
```tsx
// app/products/page.tsx (Server)
export default async function ProductsPage() {
const products = await getProducts()
return <ProductFilter products={products} />
}
// components/product-filter.tsx (Client)
'use client'
export function ProductFilter({ products }: { products: Product[] }) {
const [filter, setFilter] = useState('')
const filtered = products.filter(p => p.name.includes(filter))
return (
<>
<input onChange={e => setFilter(e.target.value)} />
{filtered.map(p => <ProductCard key={p.id} product={p} />)}
</>
)
}
```
**Pattern 2: Children as Server Components**
```tsx
// components/client-wrapper.tsx
'use client'
export function ClientWrapper({ children }: { children: React.ReactNode }) {
const [isOpen, setIsOpen] = useState(false)
return (
<div>
<button onClick={() => setIsOpen(!isOpen)}>Toggle</button>
{isOpen && children}
</div>
)
}
// app/page.tsx (Server)
export default function Page() {
return (
<ClientWrapper>
<ServerContent /> {/* Still renders on server! */}
</ClientWrapper>
)
}
```
**Pattern 3: Providers at the boundary**
```tsx
// app/providers.tsx
'use client'
import { ThemeProvider } from 'next-themes'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
const queryClient = new QueryClient()
export function Providers({ children }: { children: React.ReactNode }) {
return (
<QueryClientProvider client={queryClient}>
<ThemeProvider attribute="class" defaultTheme="system">
{children}
</ThemeProvider>
</QueryClientProvider>
)
}
```
### Shared Data with `cache()`
```tsx
import { cache } from 'react'
export const getUser = cache(async () => {
const response = await fetch('/api/user')
return response.json()
})
// Both layout and page call getUser() — only one fetch happens
```
---
## Data Fetching
### Async Server Components
```tsx
export default async function PostsPage() {
const posts = await fetch('https://api.example.com/posts').then(r => r.json())
return <ul>{posts.map(p => <li key={p.id}>{p.title}</li>)}</ul>
}
```
### Parallel Data Fetching
```tsx
export default async function DashboardPage() {
const [user, posts, analytics] = await Promise.all([
getUser(), getPosts(), getAnalytics()
])
return <Dashboard user={user} posts={posts} analytics={analytics} />
}
```
### Streaming with Suspense
```tsx
import { Suspense } from 'react'
export default function DashboardPage() {
return (
<div>
<h1>Dashboard</h1>
<Suspense fallback={<StatsSkeleton />}>
<SlowStats />
</Suspense>
<Suspense fallback={<ChartSkeleton />}>
<SlowChart />
</Suspense>
</div>
)
}
```
### Caching
```tsx
// Cache indefiniRelated 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.