Back to Skills

Nextjs

Next.js 16 with App Router, Server Components, Server Actions, Cache Components. Use for React 19.2 apps, SSR, or encountering async params, proxy.ts migration, use cache errors.

reactnextjs
By secondsky
17928Updated 1 day agoTypeScriptMIT

Skill Content

# Next.js App Router - Production Patterns

**Version**: Next.js 16.0.3
**React Version**: 19.2.0
**Node.js**: 20.9+
**Last Verified**: 2025-11-21

## Table of Contents
1. [When to Use This Skill](#when-to-use-this-skill)
2. [When NOT to Use This Skill](#when-not-to-use-this-skill)
3. [Next.js 16 Breaking Changes](#nextjs-16-breaking-changes)
4. [Cache Components & Caching APIs](#cache-components--caching-apis)
5. [Server Components](#server-components)
6. [Server Actions](#server-actions)
7. [Route Handlers](#route-handlers)
8. [React 19.2 Features](#react-192-features)
9. [Metadata API](#metadata-api)
10. [Image & Font Optimization](#image--font-optimization)
11. [Top 5 Critical Errors](#top-5-critical-errors)
12. [Performance Patterns](#performance-patterns)
13. [TypeScript Configuration](#typescript-configuration)

---

## When to Use This Skill

Use this skill when you need:

- **Next.js 16 App Router patterns** (layouts, loading, error boundaries, routing)
- **Server Components** best practices (data fetching, composition, streaming)
- **Server Actions** patterns (forms, mutations, revalidation, error handling)
- **Cache Components** with `"use cache"` directive (NEW in Next.js 16)
- **New caching APIs**: `revalidateTag()`, `updateTag()`, `refresh()` (Updated in Next.js 16)
- **Migration from Next.js 15 to 16** (async params, proxy.ts, parallel routes)
- **Route Handlers** (API endpoints, webhooks, streaming responses)
- **Proxy patterns** (`proxy.ts` replaces `middleware.ts` in Next.js 16)
- **Async route params** (`params`, `searchParams`, `cookies()`, `headers()` now async)
- **Parallel routes with default.js** (breaking change in Next.js 16)
- **React 19.2 features** (View Transitions, `useEffectEvent()`, React Compiler)
- **Metadata API** (SEO, Open Graph, Twitter Cards, sitemaps)
- **Image optimization** (`next/image` with updated defaults in Next.js 16)
- **Performance optimization** (lazy loading, code splitting, PPR, ISR)

## When NOT to Use This Skill

Do NOT use this skill for:

- **Cloudflare Workers deployment** → Use `cloudflare-nextjs` skill instead
- **Pages Router patterns** → This skill covers App Router ONLY (Pages Router is legacy)
- **Authentication libraries** → Use `clerk-auth`, `auth-js`, or other auth-specific skills
- **Database integration** → Use `cloudflare-d1`, `drizzle-orm-d1`, or database-specific skills
- **UI component libraries** → Use `tailwind-v4-shadcn` skill for Tailwind + shadcn/ui
- **State management** → Use `zustand-state-management`, `tanstack-query` skills
- **Form libraries** → Use `react-hook-form-zod` skill

---

## Next.js 16 Breaking Changes

**CRITICAL**: Next.js 16 has multiple breaking changes. For detailed migration steps, see `references/next-16-migration-guide.md`.

| Breaking Change | Before | After |
|-----------------|--------|-------|
| **Async params** | `params.slug` | `const { slug } = await params` |
| **Async headers** | `cookies()` sync | `await cookies()` |
| **Middleware** | `middleware.ts` | `proxy.ts` (renamed) |
| **Parallel routes** | `default.js` optional | `default.js` **required** |
| **Caching** | Auto-cached fetch | Opt-in with `"use cache"` |
| **revalidateTag()** | 1 argument | 2 arguments (tag + cacheLife) |
| **Node.js** | 18.x+ | **20.9+** required |
| **React** | 18.x | **19.2+** required |

**Quick Fix for Async Params**:
```typescript
// ✅ Next.js 16 pattern
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  return <div>{id}</div>
}
```

**Codemod**: `bunx @next/codemod@canary upgrade latest`

**See**: `references/next-16-migration-guide.md` for complete migration guide with examples.

---

## Cache Components & Caching APIs

### "use cache" Directive (NEW in Next.js 16)

```typescript
'use cache'

export async function BlogPosts() {
  const posts = await db.posts.findMany()
  return posts.map(post => <article key={post.id}>{post.title}</article>)
}
```

### Caching APIs Summary

| API | Purpose | Example |
|-----|---------|---------|
| `"use cache"` | Opt-in component/function caching | `'use cache'` at top |
| `revalidateTag()` | Invalidate by tag | `revalidateTag('posts', 'max')` |
| `updateTag()` | Update cache without revalidation | `updateTag('posts', newData)` |
| `refresh()` | Refresh current page | `refresh()` |
| `revalidatePath()` | Invalidate by path | `revalidatePath('/posts')` |

### PPR (Partial Prerendering)

```typescript
// next.config.ts
const config = { experimental: { ppr: true } }

// page.tsx
export const experimental_ppr = true

export default function Page() {
  return (
    <>
      <StaticHeader />
      <Suspense fallback={<Skeleton />}>
        <DynamicContent />
      </Suspense>
    </>
  )
}
```

**See**: `references/caching-apis.md` for complete caching API reference with ISR, tag-based revalidation, and advanced patterns.

---

## Server Components

Server Components are the **default** in App Router. They run on the server and can fetch data, access databases, and keep logic server-side.

```typescript
// app/posts/page.tsx (Server Component by default)
export default async function PostsPage() {
  const posts = await db.posts.findMany()
  return <div>{posts.map(p => <article key={p.id}>{p.title}</article>)}</div>
}
```

### Streaming with Suspense

```typescript
import { Suspense } from 'react'

export default function Page() {
  return (
    <div>
      <Header />
      <Suspense fallback={<Skeleton />}>
        <Posts />
      </Suspense>
    </div>
  )
}
```

### Server vs Client Components

| Server Components | Client Components |
|-------------------|-------------------|
| Data fetching, DB access | Interactivity (onClick) |
| Sensitive logic | React hooks (useState) |
| Large dependencies | Browser APIs |
| Static content | Real-time updates |

**Client Component** (requires `'use client'`):
```typescript
'use client'
import { useState } from 'react'
export function Counter() {
  const [count, setCount] = useState(0)
  return <button onClick={() => setCount(count + 1)}>{count}</button>
}
```

---

## Server Actions

Server Actions are async functions that run on the server, callable from Client or Server Components.

### Basic Server Action

```typescript
// app/actions.ts
'use server'

import { revalidatePath } from 'next/cache'

export async function createPost(formData: FormData) {
  const title = formData.get('title') as string
  await db.posts.create({ data: { title } })
  revalidatePath('/posts')
}
```

### Form Handling

```typescript
// Server Component Form (simplest)
import { createPost } from './actions'

export default function NewPostPage() {
  return (
    <form action={createPost}>
      <input name="title" required />
      <button type="submit">Create</button>
    </form>
  )
}
```

### Available Patterns

| Pattern | Use Case | Reference |
|---------|----------|-----------|
| Client Form with Loading | useFormState + useFormStatus | `templates/server-action-form.tsx` |
| Error Handling | Return { error } or { success } | `references/server-actions-patterns.md` |
| Optimistic Updates | useOptimistic hook | `references/server-actions-patterns.md` |
| File Upload | FormData + blob storage | `references/server-actions-patterns.md` |
| Redirect After Action | redirect() function | `references/server-actions-patterns.md` |

**See**: `references/server-actions-patterns.md` for error handling, optimistic updates, file uploads, and advanced patterns.

---

## Route Handlers

Route Handlers are the App Router equivalent of API Routes.

```typescript
// app/api/posts/route.ts
export async function GET(request: Request) {
  const posts = await db.posts.findMany()
  return Response.json({ posts })
}

export async function POST(request: Request) {
  const body = await request.json()
  const post = await db.posts.create({ data: body })
  return Response.json({ post }, { status: 201 })
}
```

**Dynamic Routes** (with async params):
```typescript
// app/api/posts/[id]/route.ts
export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params // Await in Next.js 16
  const post = await db.posts.findUnique({ where: { id } })
  return post ? Response.json({ post }) : Response.json({ error: 'Not found' }, { status: 404 })
}
```

**See**: `templates/route-handler-api.ts` for search params, webhooks, and streaming patterns.

---

## React 19.2 Features

| Feature | Usage |
|---------|-------|
| **React Compiler** | `experimental: { reactCompiler: true }` - Auto-memoization |
| **View Transitions** | `useTransition()` + `router.push()` |
| **useEffectEvent** | Stable event handlers without deps |

---

## Metadata API

```typescript
// Static metadata
export const metadata: Metadata = {
  title: 'My Blog',
  description: 'A blog about Next.js',
  openGraph: { title: 'My Blog', images: ['/og-image.jpg'] },
}

// Dynamic metadata (await params in Next.js 16)
export async function generateMetadata({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  const post = await db.posts.findUnique({ where: { id } })
  return { title: post.title, description: post.excerpt }
}
```

---

## Image & Font Optimization

```typescript
// next/image
import Image from 'next/image'
<Image src="/profile.jpg" alt="Profile" width={500} height={500} priority />

// next/font
import { Inter } from 'next/font/google'
const inter = Inter({ subsets: ['latin'], variable: '--font-inter' })
<html className={inter.variable}>
```

**Remote images**: Configure `images.remotePatterns` in `next.config.ts`.

---

## Top 5 Critical Errors

### Error 1: `params` is a Promise

**Error**: `Type 'Promise<{ id: string }>' is not assignable to type '{ id: string }'`

**Solution**: Await params in Next.js 16:
```typescript
export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
}
```

---

### Error 2: `middleware.ts` is deprecated

**Warning**: `middleware.ts is deprecated. Use proxy.ts instead.`

**Solution**: Rename file and function:
```typescript
// Rename: middleware.ts → proxy.ts
// Rename function: middleware → proxy
export function proxy(request: NextRequest) {
  // Same logic
}
```

---

### Error 3: Parallel route missing `default.js`

**Error**: `Parallel route @modal was matched but no default.js was found`

**Solution**: Add default.tsx:
```typescript
// app/@modal/default.tsx
export default function ModalDefault() {
  return null
}
```

---

### Error 4: Cannot use React hooks in Server Component

**Error**: `You're importing a component that needs useState. It only works in a Client Component`

**Solution**: Add `'use client'`:
```typescript
'use client'

import { useState } from 'react'

export function Counter() {
  const [count, setCount] = useState(0)
  return <button onClick={() => setCount(count + 1)}>{count}</button>
}
```

---

### Error 5: `fetch()` not caching

**Cause**: Next.js 16 uses opt-in caching with `"use cache"`.

**Solution**: Add `"use cache"` directive:
```typescript
'use cache'

export async function getPosts() {
  const response = await fetch('/api/posts')
  return response.json()
}
```

---

**See All 18 Errors**: `references/error-catalog.md`

---

## Performance Patterns

| Pattern | Usage |
|---------|-------|
| **Lazy Loading** | `const HeavyComp = dynamic(() => import('./Heavy'), { ssr: false })` |
| **Code Splitting** | Automatic per route - each `page.tsx` gets own bundle |
| **Turbopack** | Default in Next.js 16, opt out with `--webpack` flag |
| **PPR** | `experimental: { ppr: true }` + `<Suspense>` boundaries |

---

## TypeScript Configuration

```json
{
  "compilerOptions": {
    "strict": true,
    "baseUrl": ".",
    "paths": { "@/*": ["./*"] }
  }
}
```

---

## When to Load References

| Reference | Load When... |
|-----------|--------------|
| `next-16-migration-guide.md` | Migrating from Next.js 15, async params errors, proxy.ts setup |
| `server-actions-patterns.md` | Error handling, optimistic updates, file uploads, advanced forms |
| `caching-apis.md` | ISR, tag-based revalidation, updateTag(), refresh(), PPR details |
| `error-catalog.md` | Debugging any Next.js error, comprehensive error solutions |
| `top-errors.md` | Quick fixes for the 5 most common Next.js errors |

---

## Bundled Resources

| Type | Files |
|------|-------|
| **References** | `error-catalog.md`, `top-errors.md`, `next-16-migration-guide.md`, `server-actions-patterns.md`, `caching-apis.md` |
| **Templates** | `async-params-page.tsx`, `server-action-form.tsx`, `route-handler-api.ts`, `cache-component-use-cache.tsx`, `parallel-routes-with-default.tsx`, `proxy-migration.ts` |

---

## Related Skills

| Skill | Purpose |
|-------|---------|
| `cloudflare-nextjs` | Deploy to Cloudflare Workers |
| `tailwind-v4-shadcn` | Styling |
| `clerk-auth` | Authentication |
| `drizzle-orm-d1` | Database |
| `react-hook-form-zod` | Forms |
| `zustand-state-management` | Client state |

**Official Docs**: https://nextjs.org/docs | **App Router**: https://nextjs.org/docs/app

---

**Version**: Next.js 16.0.0 | React 19.2.0 | Node.js 20.9+ | TypeScript 5.3+
**Production Tested**: E-commerce, SaaS, content sites | **Token Savings**: 65-70%

How to use

  1. Copy the skill content above
  2. Create a .claude/skills directory in your project
  3. Save as .claude/skills/claude-skills-nextjs.md
  4. Use /claude-skills-nextjs in Claude Code to invoke this skill

Claude Code Skills Collection

170 production-ready skills for Claude Code CLI

Version 3.3.1 | Last Updated: 2026-05-14

<div align="center">

🔌 Platform Support

This repository uses Claude Plugin Patterns — natively supported by:

PlatformStatusNotes
Claude CodeNativeFull marketplace support
Factory DroidNativeFull marketplace support
</div> **For all other Platforms like opencode, codex and others, you can use https://github.com/enulus/OpenPackage **

A curated collection of battle-tested skills for building modern web applications with Cloudflare, AI integrations, React, Tailwind, and more.

PS: if skills.sh warns about any skill: Their scan process is a outdated LLM which flags newest versions pins (like in ZOD) as non existent and by that potentially malicous.


Quick Start

Marketplace Installation (Recommended)

# Add the marketplace
/plugin marketplace add https://github.com/secondsky/claude-skills

# Install individual skills as needed
/plugin install cloudflare-d1@claude-skills
/plugin install tailwind-v4-shadcn@claude-skills
/plugin install ai-sdk-core@claude-skills

See MARKETPLACE.md for complete catalog of all 170 skills.

Bulk Installation (Contributors)

# Clone the repository
git clone https://github.com/secondsky/claude-skills.git
cd claude-skills

# Install all 170 skills at once
./scripts/install-all.sh

# Or install individual skills
./scripts/install-skill.sh cloudflare-d1

Repository Structure

This repository contains 170 production-tested skills for Claude Code, each focused on a specific technology or capability.

Individual Skills: Each skill is a standalone unit with:

  • SKILL.md - Core knowledge and guidance
  • Templates - Working code examples
  • References - Extended documentation
  • Scripts - Helper utilities

Installation Options:

  1. Individual - Install only the skills you need via marketplace
  2. Bulk - Install all 170 skills using ./scripts/install-all.sh

Available Skills (170 Individual Skills)

Each skill is individually installable. Install only the skills you need.

Full Catalog: See MARKETPLACE.md for detailed listings.

Categories

CategorySkillsExamples
tooling29turborepo, plan-interview, code-review
frontend26nuxt-v4, nuxt-v5, tailwind-v4-shadcn, tanstack-query, nuxt-studio, maz-ui, threejs
cloudflare21cloudflare-d1, cloudflare-workers-ai, cloudflare-agents
ai20openai-agents, claude-api, ai-sdk-core
api16api-design-principles, graphql-implementation
web10hono-routing, firecrawl-scraper, web-performance
mobile7swift-best-practices, react-native-app, react-native-skills
database6drizzle-orm-d1, neon-vercel-postgres, supabase-postgres-best-practices
security6csrf-protection, access-control-rbac
auth4better-auth
testing4vitest-testing, playwright-testing
design4design-review, design-system-creation
woocommerce4woocommerce-backend-dev
cms4hugo, sveltia-cms, wordpress-plugin-core
architecture3microservices-patterns, architecture-patterns
data3sql-query-optimization, recommendation-engine
seo2seo-optimizer, seo-keyword-cluster-builder
documentation1technical-specification

How It Works

Auto-Discovery

Claude Code automatically checks ~/.claude/skills/ for relevant skills before planning tasks:

User: "Set up a Cloudflare Worker with D1 database"
           ↓
Claude: [Checks skills automatically]
           ↓
Claude: "Found cloudflare-d1 skills.
         These prevent 12 documented errors. Use them?"
           ↓
User: "Yes"
           ↓
Result: Production-ready setup, zero errors, ~65% token savings

Note: Due to token limits, not all skills may be visible at once. See ⚠️ Important: Token Limits below.

Skill Structure

Each skill includes:

skills/[skill-name]/
├── SKILL.md              # Complete documentation
├── .claude-plugin/
│   └── plugin.json       # Plugin metadata
├── templates/            # Ready-to-copy templates
├── scripts/              # Automation scripts
└── references/           # Extended documentation

Recent Additions

May 2026

Supply Chain Security (cross-cutting):

  • dependency-upgrade expanded with Socket CLI integration — proactive malicious package detection, typosquatting alerts, and CI/CD security gates. New 418-line reference guide, 2 GitHub Actions templates, and expanded supply chain security comparison (3 tools)
  • 31 skills now include "Secure Installation" guidance — contextually-tailored security sections across all high-risk skill categories (scaffolding, MCP/agent SDKs, multi-provider installs, Docker, CI/CD). Covers 8 Bun skills, 5 Nuxt skills, 6 Cloudflare skills, 4 AI/agent skills, and 8 frontend/tooling skills
  • Supply chain security is now a first-class cross-cutting concern woven into the skill collection — not a standalone topic

February - April 2026

Full-Stack Frameworks:

  • nuxt-v5 (v1.0.0) - Full Nuxt 5 support with 4 skills (core, data, server, production), 3 diagnostic agents, and interactive setup wizard
  • supabase-postgres-best-practices - 30 Postgres optimization rules from Supabase across 8 categories
  • threejs (v1.0.0) - 3D web graphics: scenes, geometries, shaders, animations, post-processing

Infrastructure:

  • JSON schema validation - Automated plugin.json validation with CI support
  • GitHub issue templates - Skill-specific issue templates for bug reports, feature requests, and submissions

Plugin Enhancements:

  • mutation-testing - Added Bun native runner support
  • dependency-upgrade - Added supply chain security content

December 2025 - January 2026

Frontend Expansion:

  • nuxt-studio (v1.0.0) - Visual CMS for Nuxt Content with live preview, OAuth auth, and R2 storage integration
  • maz-ui (v1.0.0) - 50+ Vue/Nuxt components with theming, i18n, form generation, and 14 composables

Developer Workflow:

  • plan-interview (v2.0.0) - Adaptive interview-driven spec generation with autonomous quality review
  • turborepo (v2.8.0) - Updated to official Vercel skill with enhanced monorepo build optimization

Mobile Development:

  • react-native-skills (v1.0.0) - React Native & Expo best practices with performance optimization patterns

Enhanced Authentication:

  • better-auth (v2.2.0) - Expanded to 18 framework integrations with 30+ authentication plugins

⚠️ Important: Token Limits

Skill Visibility Constraint

Claude Code has a 15,000 character limit for the total size of skill descriptions in the system prompt. This limit also applies to commands and agents.

What this means:

  • Not all 170 skills may be visible in Claude's context at once
  • Skills are loaded based on relevance and available token budget
  • You can verify how many skills Claude currently sees by asking: "How many skills do you see in your system prompt?"

Checking Visible Skills

To verify which skills are currently loaded:

# Ask Claude Code directly
"Check what skills/plugins you see in your system prompt"

Claude will report something like: "85 of 170 skills visible due to token limits"

Workaround: Increase Token Budget

You can double the headroom for skill descriptions by setting an environment variable:

# Increase limit to 30,000 characters
export SLASH_COMMAND_TOOL_CHAR_BUDGET=30000

# Then launch Claude Code
claude

This gives you approximately 2x more skill visibility in the system prompt.

Note: This is a temporary workaround. The Claude Code team is working on better solutions for skill discovery and loading.


Token Efficiency

MetricManual SetupWith SkillsSavings
Average Tokens12,000-15,0004,000-5,000~65%
Typical Errors2-4 per service0 (prevented)100%
Setup Time2-4 hours15-45 minutes~80%

Across all 170 skills: 400+ documented errors prevented.


Contributing

Prerequisites for Contributors

Install the official plugin development toolkit:

/plugin install plugin-dev@claude-code-marketplace

This provides:

  • /plugin-dev:create-plugin command (8-phase guided workflow)
  • 7 comprehensive skills (hooks, MCP, structure, agents, commands, skills)
  • 2 specialized agents (agent-creator, plugin-validator)

Quick Steps

  1. Create skill directory in plugins/
  2. Add SKILL.md with YAML frontmatter
  3. Run ./scripts/sync-plugins.sh
  4. Submit pull request

See CONTRIBUTING.md and PLUGIN_DEV_BEST_PRACTICES.md for detailed guidelines.


Documentation

DocumentPurpose
START_HERE.mdStart here! Quick navigation guide
PLUGIN_DEV_BEST_PRACTICES.mdRepository-specific best practices (marketplace, budget, quality)
MARKETPLACE.mdFull skill catalog and installation guide
MARKETPLACE_MANAGEMENT.mdTechnical infrastructure (plugin.json, scripts, validation)
CLAUDE.mdProject context and development standards
CONTRIBUTING.mdContribution guidelines

Links


Built with ❤️ by Claude Skills Maintainers

View source on GitHub