nextjs-app-router-expert

Expert in Next.js 14/15 App Router architecture, React Server Components (RSC), Server Actions, and modern full-stack React development. Specializes in routing patterns, data fetching strategies, caching, streaming, and deployment optimization.

85 stars

Best use case

nextjs-app-router-expert is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Expert in Next.js 14/15 App Router architecture, React Server Components (RSC), Server Actions, and modern full-stack React development. Specializes in routing patterns, data fetching strategies, caching, streaming, and deployment optimization.

Teams using nextjs-app-router-expert should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/nextjs-app-router-expert/SKILL.md --create-dirs "https://raw.githubusercontent.com/curiositech/some_claude_skills/main/.claude/skills/nextjs-app-router-expert/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/nextjs-app-router-expert/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How nextjs-app-router-expert Compares

Feature / Agentnextjs-app-router-expertStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Expert in Next.js 14/15 App Router architecture, React Server Components (RSC), Server Actions, and modern full-stack React development. Specializes in routing patterns, data fetching strategies, caching, streaming, and deployment optimization.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Next.js App Router Expert

## Overview

Expert in Next.js 14/15 App Router architecture, React Server Components (RSC), Server Actions, and modern full-stack React development. Specializes in routing patterns, data fetching strategies, caching, streaming, and deployment optimization.

## When to Use

- Starting a new Next.js project with App Router
- Migrating from Pages Router to App Router
- Implementing complex routing patterns (parallel, intercepting routes)
- Optimizing data fetching with RSC and caching
- Setting up Server Actions for mutations
- Configuring middleware for auth/redirects
- Debugging hydration errors or RSC issues
- Deploying to Vercel, Cloudflare, or self-hosted

## Capabilities

### Routing Architecture
- File-based routing with `app/` directory
- Dynamic routes (`[slug]`, `[...catchAll]`, `[[...optional]]`)
- Route groups `(group)` for organization
- Parallel routes `@modal`, `@sidebar`
- Intercepting routes `(.)`, `(..)`, `(..)(..)`
- Loading and error boundaries per route segment

### React Server Components
- Server vs Client component boundaries
- `'use client'` directive placement
- Composition patterns (server wrapping client)
- Streaming with Suspense boundaries
- Progressive rendering strategies

### Data Fetching
- `fetch()` with automatic deduplication
- Caching strategies (`force-cache`, `no-store`, `revalidate`)
- `generateStaticParams()` for static generation
- Incremental Static Regeneration (ISR)
- On-demand revalidation with `revalidatePath()` / `revalidateTag()`

### Server Actions
- Form mutations with `'use server'`
- Optimistic updates with `useOptimistic`
- Progressive enhancement (works without JS)
- Error handling and validation
- Redirect after mutation

### Middleware & Edge
- `middleware.ts` for auth, redirects, rewrites
- Edge Runtime vs Node.js Runtime
- Geolocation and conditional routing
- A/B testing and feature flags

### Performance Optimization
- Image optimization with `next/image`
- Font optimization with `next/font`
- Script loading strategies
- Bundle analysis and code splitting
- Partial prerendering (PPR)

## Dependencies

Works well with:
- `react-performance-optimizer` - React-specific performance patterns
- `vercel-deployment` - Vercel deployment configuration
- `cloudflare-worker-dev` - Edge deployment patterns
- `postgresql-optimization` - Database queries for RSC

## Examples

### Basic Route Structure
```
app/
├── layout.tsx          # Root layout (required)
├── page.tsx            # Home page (/)
├── loading.tsx         # Loading UI
├── error.tsx           # Error boundary
├── not-found.tsx       # 404 page
├── blog/
│   ├── page.tsx        # /blog
│   └── [slug]/
│       ├── page.tsx    # /blog/:slug
│       └── loading.tsx # Per-route loading
└── (auth)/             # Route group (no URL impact)
    ├── login/
    │   └── page.tsx    # /login
    └── register/
        └── page.tsx    # /register
```

### Server Component with Data Fetching
```typescript
// app/posts/page.tsx
import { Suspense } from 'react';

async function getPosts() {
  const res = await fetch('https://api.example.com/posts', {
    next: { revalidate: 3600 }, // ISR: revalidate every hour
  });
  return res.json();
}

export default async function PostsPage() {
  const posts = await getPosts();

  return (
    <main>
      <h1>Blog Posts</h1>
      <Suspense fallback={<PostsSkeleton />}>
        <PostList posts={posts} />
      </Suspense>
    </main>
  );
}
```

### Server Action Form
```typescript
// app/contact/page.tsx
import { redirect } from 'next/navigation';
import { revalidatePath } from 'next/cache';

async function submitContact(formData: FormData) {
  'use server';

  const email = formData.get('email') as string;
  const message = formData.get('message') as string;

  // Validate
  if (!email || !message) {
    throw new Error('Email and message required');
  }

  // Save to database
  await db.contacts.create({ email, message });

  // Revalidate and redirect
  revalidatePath('/contact');
  redirect('/contact/success');
}

export default function ContactPage() {
  return (
    <form action={submitContact}>
      <input name="email" type="email" required />
      <textarea name="message" required />
      <button type="submit">Send</button>
    </form>
  );
}
```

### Parallel Routes (Modal Pattern)
```
app/
├── layout.tsx
├── page.tsx
├── @modal/
│   ├── default.tsx     # Empty state when no modal
│   └── (.)photo/[id]/
│       └── page.tsx    # Intercept /photo/[id] as modal
└── photo/[id]/
    └── page.tsx        # Full page when direct navigation
```

```typescript
// app/layout.tsx
export default function Layout({
  children,
  modal,
}: {
  children: React.ReactNode;
  modal: React.ReactNode;
}) {
  return (
    <>
      {children}
      {modal}
    </>
  );
}
```

### Middleware for Auth
```typescript
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const token = request.cookies.get('auth-token');
  const isAuthPage = request.nextUrl.pathname.startsWith('/login');
  const isProtectedPage = request.nextUrl.pathname.startsWith('/dashboard');

  // Redirect authenticated users away from login
  if (isAuthPage && token) {
    return NextResponse.redirect(new URL('/dashboard', request.url));
  }

  // Redirect unauthenticated users to login
  if (isProtectedPage && !token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/dashboard/:path*', '/login'],
};
```

### Static Generation with Dynamic Params
```typescript
// app/blog/[slug]/page.tsx
import { notFound } from 'next/navigation';

export async function generateStaticParams() {
  const posts = await fetch('https://api.example.com/posts').then(r => r.json());

  return posts.map((post: { slug: string }) => ({
    slug: post.slug,
  }));
}

export async function generateMetadata({ params }: { params: { slug: string } }) {
  const post = await getPost(params.slug);

  return {
    title: post?.title ?? 'Post Not Found',
    description: post?.excerpt,
  };
}

export default async function PostPage({ params }: { params: { slug: string } }) {
  const post = await getPost(params.slug);

  if (!post) {
    notFound();
  }

  return (
    <article>
      <h1>{post.title}</h1>
      {/* NOTE: Always sanitize HTML content with DOMPurify before rendering */}
      <div>{post.content}</div>
    </article>
  );
}
```

### Streaming with Suspense
```typescript
// app/dashboard/page.tsx
import { Suspense } from 'react';

export default function DashboardPage() {
  return (
    <div className="grid grid-cols-2 gap-4">
      {/* These load in parallel and stream in as ready */}
      <Suspense fallback={<CardSkeleton />}>
        <RevenueCard />
      </Suspense>
      <Suspense fallback={<CardSkeleton />}>
        <UsersCard />
      </Suspense>
      <Suspense fallback={<TableSkeleton />}>
        <RecentOrders />
      </Suspense>
    </div>
  );
}

// Each component fetches its own data
async function RevenueCard() {
  const revenue = await getRevenue(); // Server-side fetch
  return <Card title="Revenue" value={revenue} />;
}
```

## Best Practices

1. **Server Components by default** - Only add `'use client'` when needed for interactivity
2. **Colocate data fetching** - Fetch data in the component that needs it
3. **Use Suspense boundaries** - Wrap async components for streaming
4. **Leverage caching** - Use `revalidate` and tags for efficient caching
5. **Progressive enhancement** - Server Actions work without JavaScript
6. **Route groups for organization** - Use `(folder)` to organize without affecting URLs
7. **Error boundaries per segment** - Add `error.tsx` to critical routes
8. **Metadata API** - Use `generateMetadata` for dynamic SEO
9. **Sanitize user content** - Always use DOMPurify or similar when rendering HTML

## Common Pitfalls

- **Hydration mismatches** - Server/client rendering differences (dates, random values)
- **Over-using 'use client'** - Pushing client boundary too high in the tree
- **Waterfall fetching** - Not parallelizing independent data fetches
- **Missing loading states** - Forgetting `loading.tsx` or Suspense boundaries
- **Stale data** - Not invalidating cache after mutations
- **Large client bundles** - Importing server-only code in client components
- **XSS vulnerabilities** - Rendering unsanitized HTML from user input

Related Skills

web-design-expert

85
from curiositech/some_claude_skills

Creates unique web designs with brand identity, color palettes, typography, and modern UI/UX patterns. Use for brand identity development, visual design systems, layout composition, and responsive web design. Activate on "web design", "brand identity", "color palette", "UI design", "visual design", "layout". NOT for typography details (use typography-expert), color theory deep-dives (use color-theory-expert), design system tokens (use design-system-creator), or code implementation without design direction.

typography-expert

85
from curiositech/some_claude_skills

Master typographer specializing in font pairing, typographic hierarchy, OpenType features, variable fonts, and performance-optimized web typography. Use for font selection, type scales, web font optimization, and typographic systems. Activate on "typography", "font pairing", "type scale", "variable fonts", "web fonts", "OpenType", "font loading". NOT for logo design, icon fonts, general CSS styling, or image-based typography.

test-automation-expert

85
from curiositech/some_claude_skills

Comprehensive test automation specialist covering unit, integration, and E2E testing strategies. Expert in Jest, Vitest, Playwright, Cypress, pytest, and modern testing frameworks. Guides test pyramid design, coverage optimization, flaky test detection, and CI/CD integration. Activate on 'test strategy', 'unit tests', 'integration tests', 'E2E testing', 'test coverage', 'flaky tests', 'mocking', 'test fixtures', 'TDD', 'BDD', 'test automation'. NOT for manual QA processes, load/performance testing (use performance-engineer), or security testing (use security-auditor).

terraform-iac-expert

85
from curiositech/some_claude_skills

Terraform and OpenTofu infrastructure as code — module design, state management, multi-environment setups, remote backends, secrets management, CI/CD integration. NOT for Pulumi, CDK, Ansible, or Kubernetes manifests.

seo-visibility-expert

85
from curiositech/some_claude_skills

Comprehensive SEO, discoverability, and AI crawler optimization for web projects. Use for technical SEO audits, llms.txt/robots.txt setup, schema markup, social launch strategies (Product Hunt, HN, Reddit), and Answer Engine Optimization (AEO). Activate on 'SEO', 'discoverability', 'llms.txt', 'robots.txt', 'Product Hunt', 'launch strategy', 'get traffic', 'be found', 'search ranking'. NOT for paid advertising, PPC campaigns, or social media content creation (use marketing skills).

reactflow-expert

85
from curiositech/some_claude_skills

Builds DAG visualizations using ReactFlow v12 with custom nodes, ELKjs auto-layout, Zustand state management, and live state updates via WebSocket. Use when implementing workflow visualization dashboards, creating custom agent node components, integrating ELK layout algorithms, or wiring execution state into React components. Activate on "ReactFlow", "workflow visualization", "DAG visualization", "ELKjs", "custom nodes", "node-based editor", "graph visualization". NOT for writing Mermaid diagrams (use mermaid-graph-writer), general React development, or static diagram rendering.

pwa-expert

85
from curiositech/some_claude_skills

Progressive Web App development with Service Workers, offline support, and app-like behavior. Use for caching strategies, install prompts, push notifications, background sync. Activate on "PWA", "Service Worker", "offline", "install prompt", "beforeinstallprompt", "manifest.json", "workbox", "cache-first". NOT for native app development (use React Native), general web performance (use performance docs), or server-side rendering.

physics-rendering-expert

85
from curiositech/some_claude_skills

Real-time rope/cable physics using Position-Based Dynamics (PBD), Verlet integration, and constraint solvers. Expert in quaternion math, Gauss-Seidel/Jacobi solvers, and tangling detection. Activate on 'rope simulation', 'PBD', 'Position-Based Dynamics', 'Verlet', 'constraint solver', 'quaternion', 'cable dynamics', 'cloth simulation', 'leash physics'. NOT for fluid dynamics (SPH/MPM), fracture simulation (FEM), offline cinematic physics, molecular dynamics, or general game physics engines (use Unity/Unreal built-ins).

photo-content-recognition-curation-expert

85
from curiositech/some_claude_skills

Expert in photo content recognition, intelligent curation, and quality filtering. Specializes in face/animal/place recognition, perceptual hashing for de-duplication, screenshot/meme detection, burst photo selection, and quick indexing strategies. Activate on 'face recognition', 'face clustering', 'perceptual hash', 'near-duplicate', 'burst photo', 'screenshot detection', 'photo curation', 'photo indexing', 'NSFW detection', 'pet recognition', 'DINOHash', 'HDBSCAN faces'. NOT for GPS-based location clustering (use event-detection-temporal-intelligence-expert), color palette extraction (use color-theory-palette-harmony-expert), semantic image-text matching (use clip-aware-embeddings), or video analysis/frame extraction.

national-expungement-expert

85
from curiositech/some_claude_skills

Criminal record expungement laws across all 50 US states and DC — eligibility rules, waiting periods, filing processes, fees, Clean Slate laws, automatic expungement provisions. NOT for active criminal defense, immigration consequences, or federal record sealing.

metal-shader-expert

85
from curiositech/some_claude_skills

20 years Weta/Pixar experience in real-time graphics, Metal shaders, and visual effects. Expert in MSL shaders, PBR rendering, tile-based deferred rendering (TBDR), and GPU debugging. Activate on 'Metal shader', 'MSL', 'compute shader', 'vertex shader', 'fragment shader', 'PBR', 'ray tracing', 'tile shader', 'GPU profiling', 'Apple GPU'. NOT for WebGL/GLSL (different architecture), general OpenGL (deprecated on Apple), CUDA (NVIDIA only), or CPU-side rendering optimization.

llm-router

85
from curiositech/some_claude_skills

Selects the optimal LLM model and provider for each task based on complexity, cost budget, and capability requirements. Routes cheap tasks to Haiku/GPT-4o-mini and complex tasks to Sonnet/Opus/o1. Use when deciding which model to call, optimizing LLM costs, or building multi-model agent systems. Activate on "which model", "model selection", "route to model", "LLM cost", "model routing", "cheap vs expensive model". NOT for prompt engineering (use prompt-engineer), model fine-tuning, or training custom models.