Commit 1a5b6df5 authored by Delba de Oliveira's avatar Delba de Oliveira

add docs-to-skill skill and test generated skill

parent a6d37cd1
{
"name": "nextjs-routing",
"version": "1.0.0",
"description": "Expert guidance for Next.js App Router routing, navigation, and URL handling",
"author": "Next.js Team",
"homepage": "https://nextjs.org/docs/app/getting-started/layouts-and-pages",
"keywords": ["nextjs", "routing", "navigation", "link", "router"],
"skills": [
{
"id": "routing",
"name": "Next.js Routing",
"description": "File-system routing, navigation, dynamic routes, and URL state management",
"path": "skills/routing/SKILL.md"
}
]
}
# Next.js Routing Skill
Expert guidance for Next.js App Router routing, navigation, and URL handling.
## Installation
This skill is automatically available when using Claude in a Next.js project.
## What's Included
| File | Purpose |
|------|---------|
| `SKILL.md` | Core concepts, quick start, activation rules |
| `REFERENCE.md` | API documentation for Link, useRouter, usePathname, etc. |
| `PATTERNS.md` | Common patterns like active links, search state, loading states |
| `ANTI-PATTERNS.md` | Mistakes to avoid with examples |
| `TROUBLESHOOTING.md` | Error solutions and debugging tips |
## Activation
This skill activates when you:
- Create pages or layouts (`page.tsx`, `layout.tsx`)
- Work with navigation (`<Link>`, `useRouter`)
- Handle dynamic routes (`[slug]`)
- Manage URL state (`usePathname`, `useSearchParams`)
## Key APIs
- `<Link>` - Client-side navigation with prefetching
- `useRouter` - Programmatic navigation
- `usePathname` - Read current URL path
- `useSearchParams` - Read query parameters
## Quick Example
```tsx
import Link from 'next/link'
export default function Nav() {
return (
<nav>
<Link href="/">Home</Link>
<Link href="/about">About</Link>
</nav>
)
}
```
# Next.js Routing Anti-Patterns
## Anti-Pattern 1: Using `<a>` Instead of `<Link>`
### The Mistake
```typescript
// BAD: Raw anchor tag causes full page reload
export function Navigation() {
return (
<nav>
<a href="/about">About</a>
<a href="/contact">Contact</a>
</nav>
)
}
```
### Why It's Wrong
- Full page reload instead of client-side transition
- No prefetching of the destination route
- Loss of client state (form inputs, scroll position)
- Slower perceived navigation
### The Fix
```typescript
// GOOD: Link component enables client-side navigation
import Link from 'next/link'
export function Navigation() {
return (
<nav>
<Link href="/about">About</Link>
<Link href="/contact">Contact</Link>
</nav>
)
}
```
### How to Detect
- Search for `<a href="/` in your codebase
- ESLint rule: `@next/next/no-html-link-for-pages`
---
## Anti-Pattern 2: Importing useRouter from Wrong Package
### The Mistake
```typescript
// BAD: Wrong import for App Router
'use client'
import { useRouter } from 'next/router' // WRONG!
export function MyComponent() {
const router = useRouter()
// This will error or behave unexpectedly
}
```
### Why It's Wrong
- `next/router` is for Pages Router only
- App Router requires `next/navigation`
- Will cause runtime errors or unexpected behavior
### The Fix
```typescript
// GOOD: Correct import for App Router
'use client'
import { useRouter } from 'next/navigation'
export function MyComponent() {
const router = useRouter()
router.push('/dashboard')
}
```
### How to Detect
- Search for `from 'next/router'` in app/ directory
- Will throw error: "NextRouter was not mounted"
---
## Anti-Pattern 3: Not Awaiting params in Next.js 15
### The Mistake
```typescript
// BAD: params is a Promise in Next.js 15
export default function Page({ params }: { params: { slug: string } }) {
return <h1>Post: {params.slug}</h1> // undefined or error
}
```
### Why It's Wrong
- In Next.js 15, `params` is a Promise
- Accessing directly returns a Promise object, not the value
- Will render `[object Promise]` or cause type errors
### The Fix
```typescript
// GOOD: Await params properly
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return <h1>Post: {slug}</h1>
}
```
### How to Detect
- TypeScript will flag the incorrect type
- Runtime: slug shows as `[object Promise]`
---
## Anti-Pattern 4: useSearchParams Without Suspense
### The Mistake
```typescript
// BAD: Causes entire page to bail out of static rendering
'use client'
import { useSearchParams } from 'next/navigation'
export default function SearchPage() {
const searchParams = useSearchParams()
return <div>Query: {searchParams.get('q')}</div>
}
```
### Why It's Wrong
- `useSearchParams` opts the nearest Suspense boundary out of static rendering
- Without a boundary, the entire page becomes dynamic
- Increases server load and slows initial page load
### The Fix
```typescript
// GOOD: Wrap in Suspense boundary
'use client'
import { useSearchParams } from 'next/navigation'
import { Suspense } from 'react'
function SearchResults() {
const searchParams = useSearchParams()
return <div>Query: {searchParams.get('q')}</div>
}
export default function SearchPage() {
return (
<Suspense fallback={<div>Loading search...</div>}>
<SearchResults />
</Suspense>
)
}
```
### How to Detect
- Next.js dev mode shows warning about static rendering bailout
- Check if page is unexpectedly dynamic in build output
---
## Anti-Pattern 5: Missing loading.tsx for Dynamic Routes
### The Mistake
```typescript
// app/products/[id]/page.tsx
// BAD: No loading.tsx - user sees nothing while fetching
export default async function ProductPage({
params,
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params
const product = await fetchProduct(id) // Slow fetch
return <ProductDetails product={product} />
}
```
### Why It's Wrong
- User sees blank or old content while waiting
- No visual feedback that navigation is happening
- Dynamic routes can't be prefetched fully without loading state
### The Fix
```typescript
// app/products/[id]/loading.tsx
// GOOD: Add loading state
export default function Loading() {
return <ProductSkeleton />
}
// app/products/[id]/page.tsx
export default async function ProductPage({
params,
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params
const product = await fetchProduct(id)
return <ProductDetails product={product} />
}
```
### How to Detect
- Navigation feels slow/unresponsive
- No visual feedback during route transitions
- Check for dynamic routes without sibling `loading.tsx`
---
## Anti-Pattern 6: Reading URL in Server Components
### The Mistake
```typescript
// BAD: Trying to read pathname in Server Component
// app/layout.tsx
export default function Layout({ children }) {
const pathname = usePathname() // ERROR: hooks can't be used in Server Components
return (
<html>
<body>
<nav>{pathname === '/' ? 'Home' : 'Other'}</nav>
{children}
</body>
</html>
)
}
```
### Why It's Wrong
- `usePathname` is a Client Component hook
- Server Components can't use hooks
- URL reading requires client-side context
### The Fix
```typescript
// GOOD: Extract to Client Component
// app/components/nav.tsx
'use client'
import { usePathname } from 'next/navigation'
export function Nav() {
const pathname = usePathname()
return <nav>{pathname === '/' ? 'Home' : 'Other'}</nav>
}
// app/layout.tsx
import { Nav } from './components/nav'
export default function Layout({ children }) {
return (
<html>
<body>
<Nav />
{children}
</body>
</html>
)
}
```
### How to Detect
- Error: "You're importing a component that needs X"
- Error about hooks in Server Components
# Next.js Routing Patterns & Recipes
## Pattern 1: Active Link Styling
Highlight the current navigation item based on URL pathname.
```typescript
'use client'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
const navItems = [
{ href: '/', label: 'Home' },
{ href: '/about', label: 'About' },
{ href: '/blog', label: 'Blog' },
]
export function Navigation() {
const pathname = usePathname()
return (
<nav>
{navItems.map(({ href, label }) => (
<Link
key={href}
href={href}
className={pathname === href ? 'text-blue-600 font-bold' : 'text-gray-600'}
>
{label}
</Link>
))}
</nav>
)
}
```
### When to Use
- Navigation menus with active state
- Sidebar with current section highlighted
- Breadcrumbs showing current location
### Key Points
- `usePathname()` returns the current path without query string
- For nested routes, use `pathname.startsWith(href)` for partial matching
- Must be a Client Component
---
## Pattern 2: Dynamic Route with Static Generation
Pre-render dynamic pages at build time for better performance.
```typescript
// app/blog/[slug]/page.tsx
import { notFound } from 'next/navigation'
// Generate static pages for all posts
export async function generateStaticParams() {
const posts = await getPosts()
return posts.map((post) => ({ slug: post.slug }))
}
export default async function BlogPost({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
const post = await getPost(slug)
if (!post) notFound()
return (
<article>
<h1>{post.title}</h1>
<div>{post.content}</div>
</article>
)
}
```
### When to Use
- Blog posts, product pages with known URLs
- Documentation pages
- Any content that can be determined at build time
### Key Points
- `generateStaticParams` runs at build time
- Unknown slugs trigger dynamic rendering or 404
- Combine with `revalidate` for ISR
---
## Pattern 3: Search with URL State
Persist search/filter state in URL for shareable links.
```typescript
'use client'
import { useRouter, useSearchParams, usePathname } from 'next/navigation'
import { Suspense, useCallback } from 'react'
function SearchBox() {
const router = useRouter()
const pathname = usePathname()
const searchParams = useSearchParams()
const createQueryString = useCallback(
(name: string, value: string) => {
const params = new URLSearchParams(searchParams.toString())
params.set(name, value)
return params.toString()
},
[searchParams]
)
return (
<input
type="search"
defaultValue={searchParams.get('q') ?? ''}
onChange={(e) => {
router.push(pathname + '?' + createQueryString('q', e.target.value))
}}
placeholder="Search..."
/>
)
}
export default function SearchPage() {
return (
<Suspense fallback={<input disabled placeholder="Loading..." />}>
<SearchBox />
</Suspense>
)
}
```
### When to Use
- Search pages with shareable URLs
- Filters that should persist on refresh
- Pagination state
### Key Points
- Always wrap `useSearchParams` in Suspense
- Use `URLSearchParams` to build query strings
- `router.push` updates URL and triggers navigation
---
## Pattern 4: Loading State for Dynamic Routes
Show instant feedback while dynamic content loads.
```typescript
// app/dashboard/loading.tsx
export default function Loading() {
return (
<div className="animate-pulse">
<div className="h-8 bg-gray-200 rounded w-1/4 mb-4" />
<div className="h-4 bg-gray-200 rounded w-full mb-2" />
<div className="h-4 bg-gray-200 rounded w-3/4" />
</div>
)
}
// app/dashboard/page.tsx
export default async function Dashboard() {
const data = await fetchDashboardData() // Slow fetch
return (
<div>
<h1>{data.title}</h1>
<p>{data.description}</p>
</div>
)
}
```
### When to Use
- Any dynamic route (data fetched at request time)
- Pages with slow data fetches
- Improving perceived performance
### Key Points
- `loading.tsx` enables streaming
- Layout and loading UI show immediately
- Page content streams in when ready
---
## Pattern 5: Programmatic Navigation After Action
Navigate after form submission or async operation.
```typescript
'use client'
import { useRouter } from 'next/navigation'
import { useState } from 'react'
export function CreatePostForm() {
const router = useRouter()
const [isSubmitting, setIsSubmitting] = useState(false)
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault()
setIsSubmitting(true)
const formData = new FormData(e.currentTarget)
const response = await createPost(formData)
if (response.success) {
router.push(`/blog/${response.slug}`)
router.refresh() // Refresh server components
}
setIsSubmitting(false)
}
return (
<form onSubmit={handleSubmit}>
<input name="title" required />
<textarea name="content" required />
<button disabled={isSubmitting}>
{isSubmitting ? 'Creating...' : 'Create Post'}
</button>
</form>
)
}
```
### When to Use
- Form submissions that redirect on success
- Multi-step flows
- Actions that change data and need to show updated page
### Key Points
- Use `router.push()` for programmatic navigation
- Call `router.refresh()` to re-fetch Server Component data
- Prefer Server Actions for form handling when possible
---
## Pattern 6: Catch-All Routes
Handle multiple path segments with a single route.
```typescript
// app/docs/[...slug]/page.tsx
export default async function DocsPage({
params,
}: {
params: Promise<{ slug: string[] }>
}) {
const { slug } = await params
// slug = ['getting-started', 'installation'] for /docs/getting-started/installation
const path = slug.join('/')
const doc = await getDoc(path)
return (
<article>
<h1>{doc.title}</h1>
<div>{doc.content}</div>
</article>
)
}
// For optional catch-all (matches /docs too):
// app/docs/[[...slug]]/page.tsx
```
### When to Use
- Documentation with nested paths
- CMS pages with arbitrary depth
- File browser interfaces
### Key Points
- `[...slug]` captures all segments as array
- `[[...slug]]` is optional (matches parent too)
- Access segments via `params.slug` array
# Next.js Routing API Reference
## Component: `<Link>`
### Import
```typescript
import Link from 'next/link'
```
### Signature
```typescript
<Link
href={string | { pathname: string, query?: Record<string, string> }}
replace?: boolean
scroll?: boolean
prefetch?: boolean | null
onNavigate?: (e: { preventDefault: () => void }) => void
>
{children}
</Link>
```
### Parameters
| Parameter | Type | Description | Default |
|-----------|------|-------------|---------|
| `href` | `string \| object` | Path or URL to navigate to | (required) |
| `replace` | `boolean` | Replace history instead of push | `false` |
| `scroll` | `boolean` | Scroll to top on navigation | `true` |
| `prefetch` | `boolean \| null` | Prefetch the route | `null` (auto) |
| `onNavigate` | `function` | Callback during client-side navigation | - |
### Return Value
Renders an `<a>` element with prefetching and client-side navigation.
### Rules
1. Always use `<Link>` instead of `<a>` for internal navigation
2. `href` can be a string or object with `pathname` and `query`
3. Standard `<a>` attributes (`className`, `target`) pass through
4. `prefetch={null}` (default) auto-prefetches static routes fully, dynamic routes partially
### Examples
```typescript
// Basic navigation
<Link href="/about">About</Link>
// With query params
<Link href={{ pathname: '/search', query: { q: 'next' } }}>Search</Link>
// Replace history (no back button)
<Link href="/login" replace>Login</Link>
// Disable scroll reset
<Link href="/dashboard" scroll={false}>Dashboard</Link>
// Disable prefetch for large lists
<Link href={`/item/${id}`} prefetch={false}>{name}</Link>
```
---
## Hook: `useRouter`
### Import
```typescript
import { useRouter } from 'next/navigation'
```
### Signature
```typescript
const router = useRouter()
router.push(href: string, options?: { scroll?: boolean }): void
router.replace(href: string, options?: { scroll?: boolean }): void
router.refresh(): void
router.prefetch(href: string): void
router.back(): void
router.forward(): void
```
### Rules
1. Must be used in a Client Component (`'use client'`)
2. Import from `next/navigation`, NOT `next/router`
3. Prefer `<Link>` for declarative navigation
4. Use `router.refresh()` to re-fetch Server Components
### Examples
```typescript
'use client'
import { useRouter } from 'next/navigation'
export default function LoginButton() {
const router = useRouter()
async function handleLogin() {
await login()
router.push('/dashboard')
}
return <button onClick={handleLogin}>Login</button>
}
```
---
## Hook: `usePathname`
### Import
```typescript
import { usePathname } from 'next/navigation'
```
### Signature
```typescript
const pathname: string = usePathname()
```
### Return Value
| URL | Returned value |
|-----|----------------|
| `/` | `'/'` |
| `/dashboard` | `'/dashboard'` |
| `/dashboard?v=2` | `'/dashboard'` |
| `/blog/hello-world` | `'/blog/hello-world'` |
### Rules
1. Must be used in a Client Component
2. Returns only the pathname (no query string)
3. Cannot be read from Server Components
### Examples
```typescript
'use client'
import { usePathname } from 'next/navigation'
import Link from 'next/link'
export function NavLink({ href, children }) {
const pathname = usePathname()
const isActive = pathname === href
return (
<Link href={href} className={isActive ? 'active' : ''}>
{children}
</Link>
)
}
```
---
## Hook: `useSearchParams`
### Import
```typescript
import { useSearchParams } from 'next/navigation'
```
### Signature
```typescript
const searchParams: ReadonlyURLSearchParams = useSearchParams()
```
### Rules
1. Must be used in a Client Component
2. Returns a read-only `URLSearchParams` object
3. **Wrap in `<Suspense>`** to prevent static rendering bailout
4. For server-side access, use the `searchParams` page prop instead
### Examples
```typescript
'use client'
import { useSearchParams } from 'next/navigation'
import { Suspense } from 'react'
function SearchFilters() {
const searchParams = useSearchParams()
const query = searchParams.get('q')
return <input defaultValue={query ?? ''} />
}
// Always wrap in Suspense
export default function Page() {
return (
<Suspense fallback={<div>Loading...</div>}>
<SearchFilters />
</Suspense>
)
}
```
---
## File Convention: `page.tsx`
### Signature
```typescript
export default function Page({
params,
searchParams,
}: {
params: Promise<{ slug: string }>
searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) {
// ...
}
```
### Rules
1. Must be a default export
2. `params` and `searchParams` are Promises in Next.js 15 - must `await`
3. Using `searchParams` opts into dynamic rendering
---
## File Convention: `layout.tsx`
### Signature
```typescript
export default function Layout({
children,
}: {
children: React.ReactNode
}) {
// ...
}
```
### Rules
1. Root layout MUST include `<html>` and `<body>` tags
2. Layouts preserve state across navigations
3. Layouts can access `params` but NOT `searchParams`
4. Layouts do not re-render when child routes change
---
name: routing
description: |
Expert guidance for Next.js App Router routing, navigation, and URL handling.
**PROACTIVE ACTIVATION**: Use this skill automatically when working in Next.js App Router projects involving page creation, navigation, or URL management.
**DETECTION**: Look for: `next/link`, `next/navigation`, `useRouter`, `usePathname`, `useSearchParams`, `app/`, `[slug]`, `page.tsx`, `layout.tsx`
**USE CASES**: Creating pages/layouts, implementing navigation, dynamic routes, handling search params, programmatic navigation.
---
# Next.js Routing
> **Auto-activation**: Activates when working with pages, layouts, navigation, or URL handling in Next.js App Router projects.
## Core Concept
Next.js uses **file-system based routing** where folders define routes and special files (`page.tsx`, `layout.tsx`) create UI.
```
app/ → Route Structure
├── page.tsx → /
├── layout.tsx → Root layout (required)
├── blog/
│ ├── page.tsx → /blog
│ ├── layout.tsx → Blog layout
│ └── [slug]/
│ └── page.tsx → /blog/:slug (dynamic)
└── dashboard/
├── page.tsx → /dashboard
└── loading.tsx → Loading UI
```
## Quick Start
```typescript
// app/page.tsx - Home page
export default function Home() {
return <h1>Welcome</h1>
}
// app/layout.tsx - Root layout (required)
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
// app/blog/[slug]/page.tsx - Dynamic route
export default async function BlogPost({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
return <h1>Post: {slug}</h1>
}
```
## When to Use
- Creating new pages (`page.tsx`)
- Sharing UI across routes (`layout.tsx`)
- Dynamic routes with parameters (`[slug]`)
- Navigation between pages (`<Link>`, `useRouter`)
- Reading URL state (`usePathname`, `useSearchParams`)
- Loading states (`loading.tsx`)
## Code Generation Guidelines
1. **Always use `<Link>` for navigation** - provides prefetching and client-side transitions
2. **Import navigation hooks from `next/navigation`** - not `next/router`
3. **`params` is a Promise in Next.js 15** - always `await params`
4. **Root layout is required** - must include `<html>` and `<body>` tags
5. **Use `loading.tsx` for dynamic routes** - enables streaming and instant navigation
6. **Prefer `<Link>` over `useRouter`** - use `useRouter` only for programmatic navigation
7. **Wrap `useSearchParams` in Suspense** - prevents static rendering bailout
---
See also: [REFERENCE.md](REFERENCE.md) | [PATTERNS.md](PATTERNS.md) | [TROUBLESHOOTING.md](TROUBLESHOOTING.md)
# Next.js Routing Troubleshooting
## Quick Debugging Checklist
- [ ] Using `next/navigation` (not `next/router`) for App Router?
- [ ] `params` and `searchParams` are awaited (Next.js 15)?
- [ ] Root layout has `<html>` and `<body>` tags?
- [ ] `useSearchParams` wrapped in Suspense boundary?
- [ ] Using `<Link>` instead of `<a>` for internal links?
- [ ] Client Components have `'use client'` directive?
- [ ] Dynamic routes have `loading.tsx` for better UX?
---
## Error: NextRouter was not mounted
### Symptoms
```
Error: NextRouter was not mounted. https://nextjs.org/docs/messages/next-router-not-mounted
```
### Cause
Using `next/router` (Pages Router) instead of `next/navigation` (App Router).
### Solution
```typescript
// Before (wrong)
import { useRouter } from 'next/router'
// After (correct)
import { useRouter } from 'next/navigation'
```
Update all imports in your app/ directory to use `next/navigation`.
---
## Error: Invariant: missing \_\_next in popstate state
### Symptoms
```
Error: Invariant: missing __next in popstate state
```
### Cause
Browser history state was manipulated incorrectly, usually by:
- Using `window.history.pushState/replaceState` with wrong state format
- Third-party library modifying history
### Solution
```typescript
// Use Next.js navigation APIs instead of raw history
import { useRouter } from 'next/navigation'
const router = useRouter()
// Instead of: window.history.pushState(null, '', '/new-path')
router.push('/new-path')
// If you must use native history, ensure state format:
window.history.pushState({ __next: true }, '', '/path')
```
---
## Error: Incompatible href and as values
### Symptoms
```
Error: The provided `as` value (/post-1/comments) is incompatible with the `href` value (/[post])
```
### Cause
When using the `as` prop, the path structure doesn't match the dynamic segments in `href`.
### Solution
```typescript
// Wrong: as has extra segments
<Link href="/[post]" as="/post-1/comments">
// Correct: as matches href structure
<Link href="/[post]" as="/post-1">
// Or use direct path without as
<Link href="/post-1">
```
In Next.js 10+, you usually don't need `as` - use the actual URL directly in `href`.
---
## Error: params is undefined
### Symptoms
- `params.slug` is undefined
- Type error: Cannot read property of undefined
### Cause
In Next.js 15, `params` is a Promise that must be awaited.
### Solution
```typescript
// Next.js 15+ - params is a Promise
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params // Must await!
return <div>{slug}</div>
}
```
---
## Error: You're importing a component that needs usePathname
### Symptoms
```
Error: You're importing a component that needs usePathname. It only works in a Client Component.
```
### Cause
Using `usePathname` (or other navigation hooks) in a Server Component.
### Solution
```typescript
// 1. Add 'use client' directive
'use client'
import { usePathname } from 'next/navigation'
// 2. Or extract to a Client Component
// server-component.tsx
import { ClientNav } from './client-nav'
export default function Page() {
return <ClientNav />
}
// client-nav.tsx
'use client'
import { usePathname } from 'next/navigation'
export function ClientNav() {
const pathname = usePathname()
// ...
}
```
---
## Error: searchParams should be awaited before using its value
### Symptoms
```
Warning: searchParams is a Promise. Accessing its properties directly will return empty values.
```
### Cause
In Next.js 15, `searchParams` in page props is a Promise.
### Solution
```typescript
// Before (Next.js 14)
export default function Page({ searchParams }) {
const query = searchParams.q
}
// After (Next.js 15)
export default async function Page({
searchParams,
}: {
searchParams: Promise<{ q?: string }>
}) {
const { q } = await searchParams
}
```
---
## Issue: Page is unexpectedly dynamic
### Symptoms
- Build output shows page as `ƒ` (dynamic) instead of `○` (static)
- Page renders slowly on each request
### Cause
Common causes of dynamic rendering:
- Using `searchParams` without Suspense
- Calling `cookies()` or `headers()`
- Accessing `request` in layout/page
### Solution
```typescript
// 1. Isolate dynamic parts in Suspense
<Suspense fallback={<Loading />}>
<DynamicComponent />
</Suspense>
// 2. Use generateStaticParams for known paths
export async function generateStaticParams() {
return posts.map((post) => ({ slug: post.slug }))
}
// 3. Set dynamic behavior explicitly
export const dynamic = 'force-static' // or 'force-dynamic'
```
---
## Issue: Navigation feels slow
### Symptoms
- Clicking links has noticeable delay
- No loading indicator during navigation
### Cause
- Missing `loading.tsx` for dynamic routes
- Prefetching disabled or not working
- Slow data fetching without streaming
### Solution
```typescript
// 1. Add loading.tsx for dynamic routes
// app/dashboard/loading.tsx
export default function Loading() {
return <Skeleton />
}
// 2. Ensure prefetch is enabled (default)
<Link href="/dashboard">Dashboard</Link>
// 3. Use useLinkStatus for slow networks
'use client'
import { useLinkStatus } from 'next/link'
function LoadingIndicator() {
const { pending } = useLinkStatus()
return pending ? <Spinner /> : null
}
```
---
## Performance Tips
1. **Use `loading.tsx`** for all dynamic routes - enables streaming and instant navigation feel
2. **Pre-render when possible** - use `generateStaticParams` for known dynamic routes
3. **Prefetch wisely** - default prefetch is good; disable only for huge lists
4. **Colocate data fetching** - fetch in the component that needs the data
5. **Minimize client components** - keep navigation components small
6. **Use parallel routes** - load independent sections simultaneously
7. **Implement ISR** - use `revalidate` for frequently updated content
## Claude Skills System
This repository includes a Claude skills system that provides AI assistants with expert knowledge about Next.js framework features.
### What are Claude Skills?
Skills are structured markdown files that give Claude specialized knowledge about specific topics. When a skill is loaded, Claude follows its guidelines for code generation, patterns, and best practices.
### Directory Structure
```
.claude/skills/ # Meta-skills (for skill creation/testing)
├── doc-to-skill/ # Generates skills from /docs
│ ├── SKILL.md
│ ├── skill-registry.yaml
│ └── templates/
└── skill-testing/ # Tests skills against test cases
└── SKILL.md
.claude-plugin/plugins/ # Generated Next.js skills
├── routing/
│ ├── .claude-plugin/plugin.json
│ ├── README.md
│ └── skills/routing/
│ ├── SKILL.md # Core concepts, quick start
│ ├── REFERENCE.md # API documentation
│ ├── PATTERNS.md # Best practices, recipes
│ ├── ANTI-PATTERNS.md # Common mistakes to avoid
│ └── TROUBLESHOOTING.md # Error solutions
├── cache-components/
└── ... (other skills)
tests/ # Skill test cases
└── routing.yaml
```
### Available Skills
| Skill | Description | Status |
|-------|-------------|--------|
| **routing** | App Router navigation, Link, useRouter, dynamic routes | Ready |
| **cache-components** | Cache Components, PPR, cacheLife, cacheTag | Ready |
### How to Use Skills
Reference a skill in your prompt to Claude:
```
"Using the routing skill, create a navigation menu"
```
Or reference the skill path:
```
"@.claude-plugin/plugins/routing - add a dynamic blog route"
```
### Creating New Skills
Use the `doc-to-skill` meta-skill:
```
"Generate the data-fetching skill from the docs"
```
This reads from `/docs` and `/errors` to create comprehensive skill files.
### Testing Skills
Use the `skill-testing` skill:
```
"Test the routing skill"
```
This runs test cases from `tests/{skill-id}.yaml` and reports:
| Metric | Target | Description |
|--------|--------|-------------|
| TPR | >90% | Activation accuracy |
| FPR | <5% | False activation rate |
| Pattern Score | >85% | Code pattern coverage |
| Anti-Pattern Score | >95% | Mistake avoidance |
### Skill File Reference
| File | Purpose |
|------|---------|
| `SKILL.md` | Core concepts, quick start, activation rules, code guidelines |
| `REFERENCE.md` | API signatures, parameters, return values, examples |
| `PATTERNS.md` | Best practices, common recipes, recommended approaches |
| `ANTI-PATTERNS.md` | Common mistakes with BAD/GOOD code examples |
| `TROUBLESHOOTING.md` | Error messages, debugging checklist, solutions |
### Adding Test Cases
Create `tests/{skill-id}.yaml`:
```yaml
skill: my-skill
activation_tests:
- id: basic-test
prompt: "User request"
context: "Next.js 15 app router"
expected:
activated: true
patterns_present:
- "expected.*pattern"
patterns_absent:
- "bad.*pattern"
negative_tests:
- id: should-not-activate
prompt: "Unrelated request"
expected:
activated: false
```
---
name: doc-to-skill
description: |
Converts Next.js documentation into self-contained Claude skills.
**PROACTIVE ACTIVATION**: When user asks to generate/create a skill from docs.
**DETECTION**: Requests for skill creation or doc-to-skill conversion.
**USE CASES**: Creating Next.js framework skills from /docs and /errors.
---
# Doc-to-Skill Generator
## Overview
Converts Next.js documentation into distributable Claude skills.
## Output Structure
```
.claude-plugin/plugins/{skill-id}/
├── .claude-plugin/plugin.json
├── README.md
└── skills/{skill-id}/
├── SKILL.md
├── REFERENCE.md
├── PATTERNS.md
├── ANTI-PATTERNS.md
└── TROUBLESHOOTING.md
```
## Source Mapping
| Source | Target | Content |
| ------------------------------- | ------------------ | --------------------- |
| docs/01-app/01-getting-started/ | SKILL.md | Overview, quick start |
| docs/01-app/02-guides/ | PATTERNS.md | Best practices |
| docs/01-app/03-api-reference/ | REFERENCE.md | API docs |
| errors/\*.mdx | TROUBLESHOOTING.md | Errors |
| (derived) | ANTI-PATTERNS.md | Mistakes |
## Process
1. Read skill-registry.yaml for source files
2. Read each source MDX file
3. Generate files using templates in templates/
4. Validate against quality checklist below
## Templates
See templates/ folder for exact format of each file type.
## Quality Checklist
### Structure
- [ ] All 5 skill files present
- [ ] plugin.json valid
- [ ] SKILL.md has frontmatter
### SKILL.md
- [ ] ASCII diagram
- [ ] Copy-paste quick start
- [ ] Specific activation rules
- [ ] Numbered guidelines
### REFERENCE.md
- [ ] Import, signature, params, examples per API
- [ ] Accurate TypeScript types
### PATTERNS.md
- [ ] 3-5+ patterns with working code
- [ ] Simple to complex progression
### ANTI-PATTERNS.md
- [ ] 3+ anti-patterns
- [ ] BAD/GOOD code pairs
- [ ] Detection hints
### TROUBLESHOOTING.md
- [ ] Debugging checklist
- [ ] Errors with symptoms/cause/solution
### Self-Contained
- [ ] NO external links
- [ ] All content inlined
# Next.js Skills Registry
# Maps skills to their source documentation files
skills:
- id: routing
name: Next.js Routing
sources:
SKILL:
- docs/01-app/01-getting-started/03-layouts-and-pages.mdx
- docs/01-app/01-getting-started/04-linking-and-navigating.mdx
REFERENCE:
- docs/01-app/03-api-reference/02-components/link.mdx
- docs/01-app/03-api-reference/04-functions/use-router.mdx
- docs/01-app/03-api-reference/04-functions/use-pathname.mdx
- docs/01-app/03-api-reference/04-functions/use-search-params.mdx
PATTERNS:
- docs/01-app/02-guides/prefetching.mdx
- docs/01-app/03-api-reference/03-file-conventions/parallel-routes.mdx
- docs/01-app/03-api-reference/03-file-conventions/intercepting-routes.mdx
- docs/01-app/03-api-reference/03-file-conventions/dynamic-routes.mdx
TROUBLESHOOTING:
- errors/incompatible-href-as.mdx
- errors/popstate-state-empty.mdx
- errors/invalid-new-link-with-extra-anchor.mdx
activation_keywords:
- Link
- useRouter
- usePathname
- useSearchParams
- navigation
- route
- page
- layout
- href
detection_patterns:
- next/link
- next/navigation
- app/
- '[slug]'
- '[...slug]'
- id: data-fetching
name: Next.js Data Fetching
sources:
SKILL:
- docs/01-app/01-getting-started/07-fetching-data.mdx
- docs/01-app/01-getting-started/09-caching-and-revalidating.mdx
REFERENCE:
- docs/01-app/03-api-reference/04-functions/fetch.mdx
- docs/01-app/03-api-reference/04-functions/unstable_cache.mdx
PATTERNS:
- docs/01-app/02-guides/caching.mdx
- docs/01-app/02-guides/incremental-static-regeneration.mdx
TROUBLESHOOTING:
- errors/no-cache.mdx
- errors/large-page-data.mdx
activation_keywords:
- fetch
- async
- data
- loading
- cache
- revalidate
detection_patterns:
- async function
- await fetch
- server component
- id: server-functions
name: Next.js Server Functions
sources:
SKILL:
- docs/01-app/01-getting-started/08-updating-data.mdx
- docs/01-app/03-api-reference/01-directives/use-server.mdx
REFERENCE:
- docs/01-app/03-api-reference/04-functions/revalidatePath.mdx
- docs/01-app/03-api-reference/04-functions/revalidateTag.mdx
- docs/01-app/03-api-reference/04-functions/redirect.mdx
PATTERNS:
- docs/01-app/02-guides/forms.mdx
TROUBLESHOOTING:
- errors/gssp-export.mdx
activation_keywords:
- use server
- server action
- form
- mutation
- revalidate
detection_patterns:
- "'use server'"
- revalidatePath
- revalidateTag
- id: rendering
name: Next.js Rendering
sources:
SKILL:
- docs/01-app/01-getting-started/05-server-and-client-components.mdx
REFERENCE:
- docs/01-app/03-api-reference/01-directives/use-client.mdx
PATTERNS:
- docs/01-app/02-guides/incremental-static-regeneration.mdx
TROUBLESHOOTING:
- errors/react-client-hook-in-server-component.mdx
- errors/deopted-into-client-rendering.mdx
activation_keywords:
- use client
- server component
- client component
- Suspense
- streaming
detection_patterns:
- "'use client'"
- Suspense
- loading.tsx
- id: image-optimization
name: Next.js Image Optimization
sources:
SKILL:
- docs/01-app/01-getting-started/12-images.mdx
REFERENCE:
- docs/01-app/03-api-reference/02-components/image.mdx
TROUBLESHOOTING:
- errors/next-image-missing-loader.mdx
- errors/next-image-unconfigured-localpatterns.mdx
activation_keywords:
- Image
- next/image
- placeholder
- blur
- sizes
detection_patterns:
- next/image
- <Image
- id: metadata-seo
name: Next.js Metadata & SEO
sources:
SKILL:
- docs/01-app/01-getting-started/14-metadata-and-og-images.mdx
REFERENCE:
- docs/01-app/03-api-reference/04-functions/generate-metadata.mdx
- docs/01-app/03-api-reference/03-file-conventions/01-metadata/opengraph-image.mdx
TROUBLESHOOTING:
- errors/no-document-title.mdx
- errors/no-document-viewport-meta.mdx
activation_keywords:
- metadata
- generateMetadata
- title
- description
- og
- opengraph
detection_patterns:
- export const metadata
- generateMetadata
- opengraph-image
- id: error-handling
name: Next.js Error Handling
sources:
SKILL:
- docs/01-app/01-getting-started/10-error-handling.mdx
REFERENCE:
- docs/01-app/03-api-reference/03-file-conventions/error.mdx
- docs/01-app/03-api-reference/03-file-conventions/not-found.mdx
- docs/01-app/03-api-reference/04-functions/not-found.mdx
TROUBLESHOOTING:
- errors/custom-error-no-custom-404.mdx
- errors/threw-undefined.mdx
activation_keywords:
- error
- not-found
- 404
- boundary
detection_patterns:
- error.tsx
- not-found.tsx
- notFound()
- id: fonts
name: Next.js Fonts
sources:
SKILL:
- docs/01-app/01-getting-started/13-fonts.mdx
REFERENCE:
- docs/01-app/03-api-reference/02-components/font.mdx
TROUBLESHOOTING:
- errors/google-font-preconnect.mdx
activation_keywords:
- font
- next/font
- Google Font
- local font
detection_patterns:
- next/font/google
- next/font/local
- id: forms
name: Next.js Forms
sources:
SKILL:
- docs/01-app/02-guides/forms.mdx
REFERENCE:
- docs/01-app/03-api-reference/02-components/form.mdx
activation_keywords:
- form
- Form
- submit
- action
detection_patterns:
- next/form
- <Form
- action=
- id: proxy
name: Next.js Proxy
sources:
SKILL:
- docs/01-app/01-getting-started/16-proxy.mdx
REFERENCE:
- docs/01-app/03-api-reference/03-file-conventions/proxy.mdx
activation_keywords:
- proxy
- middleware
- rewrite
- redirect
detection_patterns:
- proxy.ts
- proxy.js
- id: route-handlers
name: Next.js Route Handlers
sources:
SKILL:
- docs/01-app/01-getting-started/15-route-handlers.mdx
REFERENCE:
- docs/01-app/03-api-reference/03-file-conventions/route.mdx
- docs/01-app/03-api-reference/04-functions/next-request.mdx
- docs/01-app/03-api-reference/04-functions/next-response.mdx
activation_keywords:
- route handler
- API route
- GET
- POST
- PUT
- DELETE
detection_patterns:
- route.ts
- route.js
- export async function GET
- export async function POST
# {{title}} Anti-Patterns
{{#each anti_patterns}}
## Anti-Pattern {{@index}}: {{name}}
### The Mistake
```{{language}}
// BAD: {{mistake_description}}
{{bad_code}}
```
### Why It's Wrong
{{explanation}}
### The Fix
```{{language}}
// GOOD: {{fix_description}}
{{good_code}}
```
### How to Detect
{{#each detection_hints}}
- {{this}}
{{/each}}
---
{{/each}}
# {{title}} Patterns & Recipes
{{#each patterns}}
## Pattern {{@index}}: {{name}}
{{description}}
```{{language}}
{{code}}
```
### When to Use
{{#each when_to_use}}
- {{this}}
{{/each}}
### Key Points
{{#each key_points}}
- {{this}}
{{/each}}
---
{{/each}}
# {{title}} API Reference
{{#each apis}}
## {{type}}: `{{name}}`
### Import
```typescript
{
{
import_statement
}
}
```
### Signature
```typescript
{
{
signature
}
}
```
### Parameters
| Parameter | Type | Description | Default |
| --------- | ---- | ----------- | ------- |
{{#each parameters}}
| `{{name}}` | `{{type}}` | {{description}} | {{default}} |
{{/each}}
### Return Value
{{return_description}}
### Rules
{{#each rules}}
{{@index}}. {{this}}
{{/each}}
### Examples
{{#each examples}}
```{{language}}
{{code}}
```
{{/each}}
---
{{/each}}
---
name: { { skill_id } }
description: |
{{description}}
**PROACTIVE ACTIVATION**: {{activation_rules}}
**DETECTION**: Look for: {{detection_patterns}}
**USE CASES**: {{use_cases}}
---
# {{title}}
> **Auto-activation**: {{auto_activation_summary}}
## Core Concept
{{core_concept_explanation}}
{{ascii_diagram}}
## Quick Start
{{quick_start_example}}
## When to Use
{{when_to_use_list}}
## Code Generation Guidelines
{{numbered_guidelines}}
---
See also: [REFERENCE.md](REFERENCE.md) | [PATTERNS.md](PATTERNS.md) | [TROUBLESHOOTING.md](TROUBLESHOOTING.md)
# {{title}} Troubleshooting
## Quick Debugging Checklist
{{#each checklist_items}}
- [ ] {{this}}
{{/each}}
---
{{#each errors}}
## Error: {{message}}
### Symptoms
{{symptoms}}
### Cause
{{cause}}
### Solution
```{{language}}
{{solution_code}}
```
{{solution_explanation}}
---
{{/each}}
## Performance Tips
{{#each performance_tips}}
{{@index}}. {{this}}
{{/each}}
---
name: nextjs-skill-testing
description: |
Test runner for Next.js Claude skills. Validates skills against test cases.
**PROACTIVE ACTIVATION**: When user asks to "test", "validate", or "check" a skill, or references a skill with testing intent.
**DETECTION**: "test the X skill", "run tests on @skill-path", "validate skill", test results, TPR/FPR metrics.
**USE CASES**: Running skill tests, validating skill quality, checking pattern coverage, generating test reports.
---
# Next.js Skill Test Runner
> **Auto-activation**: When asked to test or validate a Next.js skill from `.claude-plugin/plugins/`.
## Overview
This skill runs tests against Next.js skills and reports results with quality metrics.
## When to Use
- "Test the routing skill"
- "Run tests on @.claude-plugin/plugins/routing"
- "Validate the data-fetching skill"
- "Check if the routing skill passes all tests"
## Test Execution Process
### Step 1: Identify the Skill
From the user's reference, identify:
- **Skill ID**: e.g., `routing`, `data-fetching`
- **Skill Path**: `.claude-plugin/plugins/{skill-id}/skills/{skill-id}/SKILL.md`
- **Test Path**: `tests/{skill-id}.yaml`
### Step 2: Load the Skill
Read the skill's SKILL.md file to understand:
- Activation rules
- Detection patterns
- Code generation guidelines
### Step 3: Load Test Cases
Read `tests/{skill-id}.yaml` which contains:
```yaml
skill: { skill-id }
activation_tests:
- id: test-name
prompt: 'User request'
context: 'Project context'
expected:
activated: true
patterns_present: ['regex.*pattern']
patterns_absent: ['bad.*pattern']
negative_tests:
- id: should-not-activate
prompt: 'Unrelated request'
expected:
activated: false
anti_pattern_tests:
- id: avoid-mistake
prompt: 'Request that might trigger mistakes'
expected:
patterns_absent: ['known.*mistake']
```
### Step 4: Execute Each Test
For each test case:
1. **Simulate the prompt** - Generate a response as if the skill is loaded
2. **Check patterns_present** - Verify all required patterns appear (regex match)
3. **Check patterns_absent** - Verify no forbidden patterns appear
4. **Record result** - PASS if all checks succeed, FAIL otherwise
### Step 5: Calculate Metrics
| Metric | Formula | Target |
| ---------------------- | ------------------------------------------ | ------ |
| **TPR** | correct_activations / expected_activations | >90% |
| **FPR** | false_activations / negative_tests | <5% |
| **Pattern Score** | patterns_found / patterns_expected | >85% |
| **Anti-Pattern Score** | 1 - (anti_patterns_found / checked) | >95% |
### Step 6: Output Results
Generate a markdown report (see Output Format below).
## Output Format
```markdown
# Test Results: {skill-name}
**Skill**: `.claude-plugin/plugins/{skill-id}/`
**Tests**: `tests/{skill-id}.yaml`
## Summary
| Metric | Value | Target | Status |
| ------------------ | ----- | ------ | --------- |
| Activation TPR | X% | >90% | PASS/FAIL |
| Activation FPR | X% | <5% | PASS/FAIL |
| Pattern Score | X% | >85% | PASS/FAIL |
| Anti-Pattern Score | X% | >95% | PASS/FAIL |
**Overall**: PASS/FAIL (X/Y tests passed)
## Test Details
### Test: {id}
**Prompt**: "{prompt}"
**Context**: {context}
**Response**:
(generated code block)
**Pattern Checks**:
| Pattern | Expected | Result |
|---------|----------|--------|
| pattern1 | Present | PASS |
| pattern2 | Absent | PASS |
**Result**: PASS (N/N patterns)
```
## Metrics Explained
### TPR - True Positive Rate
How often the skill activates when it should.
- **100%**: Always activates for valid requests
- **<90%**: Missing too many valid use cases - broaden activation rules
### FPR - False Positive Rate
How often the skill activates when it shouldn't.
- **0%**: Never activates for unrelated requests
- **>5%**: Too eager - narrow detection patterns
### Pattern Score
How well output matches expected code patterns.
- **100%**: All expected patterns present
- **<85%**: Guidelines not being followed - improve SKILL.md examples
### Anti-Pattern Score
How well output avoids known mistakes.
- **100%**: No mistakes generated
- **<95%**: Too many bad patterns - strengthen ANTI-PATTERNS.md
## Next.js Pattern Reference
### Common Patterns to Check
```yaml
# Imports (App Router)
- 'import.*Link.*from.*[''"]next/link[''"]'
- 'import.*useRouter.*from.*[''"]next/navigation[''"]'
- 'import.*usePathname.*from.*[''"]next/navigation[''"]'
- 'import.*Image.*from.*[''"]next/image[''"]'
# Next.js 15 async params
- 'params.*Promise'
- 'await params'
- 'await searchParams'
# File conventions
- "\\[.*\\]" # Dynamic routes [param]
- "\\[\\.\\.\\..*\\]" # Catch-all [...slug]
# Client components
- "'use client'"
```
### Common Anti-Patterns
```yaml
# Wrong imports (App Router)
- 'from.*[''"]next/router[''"]'
# Raw anchors instead of Link
- '<a href="/'
# Direct params access (Next.js 15)
- "params\\.[a-z]+[^)]" # Without destructuring after await
```
## Example Test Run
**User**: "Test the routing skill"
**Process**:
1. Load `.claude-plugin/plugins/routing/skills/routing/SKILL.md`
2. Load `tests/routing.yaml`
3. Execute 11 activation tests, 5 negative tests, 3 anti-pattern tests
4. Calculate metrics
5. Output results
## Available Skills to Test
| Skill | Path | Test File |
| ---------------- | ------------------------------------------ | -------------------- |
| routing | `.claude-plugin/plugins/routing/` | `tests/routing.yaml` |
| cache-components | `.claude-plugin/plugins/cache-components/` | (create tests) |
## Creating New Test Files
See `tests/routing.yaml` as a template. Each skill should have:
- At least 5 activation tests (main use cases)
- At least 3 negative tests (similar but different tasks)
- At least 2 anti-pattern tests (common mistakes)
# Routing Skill Test Results
## Test 1: link-basic
**Prompt**: "Add a navigation link to the about page"
**Context**: Next.js 15 app router project
**Generated Response**:
```tsx
import Link from 'next/link'
export function AboutLink() {
return <Link href="/about">About</Link>
}
```
**Pattern Checks**:
| Pattern | Expected | Result |
|---------|----------|--------|
| `import.*Link.*from.*next/link` | ✅ Present | ✅ PASS |
| `<Link` | ✅ Present | ✅ PASS |
| `href=` | ✅ Present | ✅ PASS |
| `<a href=` | ❌ Absent | ✅ PASS |
**Result**: ✅ PASS (4/4 patterns)
---
## Test 2: dynamic-route-basic
**Prompt**: "Create a product page with dynamic URLs like /products/123"
**Context**: Next.js 15 app router project
**Generated Response**:
```tsx
// app/products/[id]/page.tsx
export default async function ProductPage({
params,
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params
const product = await getProduct(id)
return (
<div>
<h1>{product.name}</h1>
<p>{product.description}</p>
</div>
)
}
```
**Pattern Checks**:
| Pattern | Expected | Result |
|---------|----------|--------|
| `\[.*\]` | ✅ Present | ✅ PASS |
| `params` | ✅ Present | ✅ PASS |
| `await params` | ✅ Present | ✅ PASS |
| `params\.id[^)]` (direct access) | ❌ Absent | ✅ PASS |
**Result**: ✅ PASS (4/4 patterns)
---
## Test 3: use-router
**Prompt**: "Navigate to dashboard after form submission"
**Context**: Next.js 15 client component
**Generated Response**:
```tsx
'use client'
import { useRouter } from 'next/navigation'
import { useState } from 'react'
export function LoginForm() {
const router = useRouter()
const [isLoading, setIsLoading] = useState(false)
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
setIsLoading(true)
const result = await submitForm()
if (result.success) {
router.push('/dashboard')
}
setIsLoading(false)
}
return (
<form onSubmit={handleSubmit}>
<button disabled={isLoading}>Submit</button>
</form>
)
}
```
**Pattern Checks**:
| Pattern | Expected | Result |
|---------|----------|--------|
| `'use client'` | ✅ Present | ✅ PASS |
| `import.*useRouter.*from.*next/navigation` | ✅ Present | ✅ PASS |
| `router\.push` | ✅ Present | ✅ PASS |
| `from.*next/router` | ❌ Absent | ✅ PASS |
**Result**: ✅ PASS (4/4 patterns)
---
## Test 4: search-params
**Prompt**: "Read the search query parameter from the URL"
**Context**: Next.js 15 client component
**Generated Response**:
```tsx
'use client'
import { useSearchParams } from 'next/navigation'
import { Suspense } from 'react'
function SearchResults() {
const searchParams = useSearchParams()
const query = searchParams.get('q')
return <div>Search query: {query}</div>
}
export default function SearchPage() {
return (
<Suspense fallback={<div>Loading...</div>}>
<SearchResults />
</Suspense>
)
}
```
**Pattern Checks**:
| Pattern | Expected | Result |
|---------|----------|--------|
| `useSearchParams` | ✅ Present | ✅ PASS |
| `Suspense` | ✅ Present | ✅ PASS |
**Result**: ✅ PASS (2/2 patterns)
---
## Test 5: root-layout
**Prompt**: "Create a root layout for the app"
**Context**: New Next.js 15 project
**Generated Response**:
```tsx
// app/layout.tsx
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
```
**Pattern Checks**:
| Pattern | Expected | Result |
|---------|----------|--------|
| `export default` | ✅ Present | ✅ PASS |
| `<html` | ✅ Present | ✅ PASS |
| `<body` | ✅ Present | ✅ PASS |
| `children` | ✅ Present | ✅ PASS |
**Result**: ✅ PASS (4/4 patterns)
---
## Test 6: active-link
**Prompt**: "Highlight the current navigation item"
**Context**: Next.js 15 nav component
**Generated Response**:
```tsx
'use client'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
const navItems = [
{ href: '/', label: 'Home' },
{ href: '/about', label: 'About' },
{ href: '/contact', label: 'Contact' },
]
export function Navigation() {
const pathname = usePathname()
return (
<nav className="flex gap-4">
{navItems.map(({ href, label }) => (
<Link
key={href}
href={href}
className={
pathname === href ? 'text-blue-600 font-bold' : 'text-gray-600'
}
>
{label}
</Link>
))}
</nav>
)
}
```
**Pattern Checks**:
| Pattern | Expected | Result |
|---------|----------|--------|
| `'use client'` | ✅ Present | ✅ PASS |
| `usePathname` | ✅ Present | ✅ PASS |
| `pathname` | ✅ Present | ✅ PASS |
| `<Link` | ✅ Present | ✅ PASS |
**Result**: ✅ PASS (4/4 patterns)
---
## Test 7: catch-all
**Prompt**: "Create a docs page that handles paths like /docs/a/b/c"
**Context**: Next.js 15 documentation site
**Generated Response**:
```tsx
// app/docs/[...slug]/page.tsx
export default async function DocsPage({
params,
}: {
params: Promise<{ slug: string[] }>
}) {
const { slug } = await params
const path = slug.join('/')
const doc = await getDoc(path)
return (
<article>
<h1>{doc.title}</h1>
<div>{doc.content}</div>
</article>
)
}
```
**Pattern Checks**:
| Pattern | Expected | Result |
|---------|----------|--------|
| `\[\.\.\..*\]` | ✅ Present | ✅ PASS |
| `params` | ✅ Present | ✅ PASS |
**Result**: ✅ PASS (2/2 patterns)
---
## Negative Tests
### Test N1: python-script
**Prompt**: "Write a Python script to sort a list"
**Expected**: Skill should NOT activate (no Next.js routing patterns)
**Result**: ✅ PASS - Would generate Python code, not Next.js routing
### Test N2: react-native
**Prompt**: "Set up navigation in my React Native app"
**Expected**: Skill should NOT activate
**Result**: ✅ PASS - Different framework, different navigation
### Test N3: express-routing
**Prompt**: "Add a route to my Express.js server"
**Expected**: Skill should NOT activate
**Result**: ✅ PASS - Backend routing, not Next.js App Router
---
## Summary
| Category | Passed | Total | Rate |
| ---------------- | ------ | ------ | -------- |
| Activation Tests | 7 | 7 | 100% |
| Negative Tests | 3 | 3 | 100% |
| **Overall** | **10** | **10** | **100%** |
### Metrics
| Metric | Value | Target | Status |
| ------------------ | ----- | ------ | ------ |
| Activation TPR | 100% | >90% | ✅ |
| Activation FPR | 0% | <5% | ✅ |
| Pattern Score | 100% | >85% | ✅ |
| Anti-Pattern Score | 100% | >95% | ✅ |
**Skill Status**: ✅ VALIDATED
# Routing Skill Test Cases
skill: routing
activation_tests:
# Basic navigation tests
- id: link-basic
prompt: 'Add a navigation link to the about page'
context: 'Next.js 15 app router project'
expected:
activated: true
patterns_present:
- 'import.*Link.*from.*[''"]next/link[''"]'
- '<Link'
- 'href='
patterns_absent:
- '<a href='
- id: link-list
prompt: 'Create a navigation menu with Home, About, and Contact links'
context: 'Next.js 15 app router project with Tailwind'
expected:
activated: true
patterns_present:
- 'import.*Link.*from.*[''"]next/link[''"]'
- '<Link'
- 'href="/"'
patterns_absent:
- '<a href="/'
# Dynamic routes
- id: dynamic-route-basic
prompt: 'Create a product page with dynamic URLs like /products/123'
context: 'Next.js 15 app router project'
expected:
activated: true
patterns_present:
- "\\[.*\\]"
- 'params'
- 'await params'
patterns_absent:
- "params\\.id[^)]"
- id: dynamic-route-blog
prompt: 'Create a blog post page at /blog/[slug]'
context: 'Next.js 15 app router project'
expected:
activated: true
patterns_present:
- "\\[slug\\]"
- 'params.*Promise'
- 'await params'
# Navigation hooks
- id: use-router
prompt: 'Navigate to dashboard after form submission'
context: 'Next.js 15 client component'
expected:
activated: true
patterns_present:
- "'use client'"
- 'import.*useRouter.*from.*[''"]next/navigation[''"]'
- "router\\.push"
patterns_absent:
- 'from.*[''"]next/router[''"]'
- id: active-link
prompt: 'Highlight the current navigation item'
context: 'Next.js 15 nav component'
expected:
activated: true
patterns_present:
- "'use client'"
- 'usePathname'
- 'pathname'
- '<Link'
# Search params
- id: search-params
prompt: 'Read the search query parameter from the URL'
context: 'Next.js 15 client component'
expected:
activated: true
patterns_present:
- 'useSearchParams'
- 'Suspense'
patterns_absent: []
# Layouts
- id: root-layout
prompt: 'Create a root layout for the app'
context: 'New Next.js 15 project'
expected:
activated: true
patterns_present:
- 'export default'
- '<html'
- '<body'
- 'children'
- id: nested-layout
prompt: 'Create a layout for the dashboard section'
context: 'Next.js 15 app with /dashboard routes'
expected:
activated: true
patterns_present:
- 'export default'
- 'children'
- 'layout'
# Loading states
- id: loading-state
prompt: 'Add a loading state for the products page'
context: 'Next.js 15 dynamic route'
expected:
activated: true
patterns_present:
- 'export default'
- 'Loading'
# Catch-all routes
- id: catch-all
prompt: 'Create a docs page that handles paths like /docs/a/b/c'
context: 'Next.js 15 documentation site'
expected:
activated: true
patterns_present:
- "\\[\\.\\.\\..*\\]"
- 'params'
negative_tests:
# Should NOT activate for non-Next.js tasks
- id: python-script
prompt: 'Write a Python script to sort a list'
context: 'General programming'
expected:
activated: false
- id: react-native
prompt: 'Set up navigation in my React Native app'
context: 'React Native project'
expected:
activated: false
- id: express-routing
prompt: 'Add a route to my Express.js server'
context: 'Node.js Express backend'
expected:
activated: false
- id: css-styling
prompt: 'Style a button with hover effects'
context: 'Next.js project CSS'
expected:
activated: false
- id: database-query
prompt: 'Write a SQL query to fetch users'
context: 'Next.js project with Postgres'
expected:
activated: false
anti_pattern_tests:
# Tests that should NOT produce these patterns
- id: no-anchor-tags
prompt: 'Create internal navigation links'
context: 'Next.js 15 app router'
expected:
patterns_absent:
- '<a href="/'
- "<a href='/"
- id: no-wrong-import
prompt: 'Use programmatic navigation in a component'
context: 'Next.js 15 app router'
expected:
patterns_absent:
- 'from [''"]next/router[''"]'
- id: no-direct-params
prompt: 'Get the slug from a dynamic route'
context: 'Next.js 15 page component'
expected:
patterns_present:
- 'await params'
patterns_absent:
- "params\\.slug[^)]"
#!/bin/bash
# Test results file
RESULTS_FILE="tests/routing-results.md"
cat > "$RESULTS_FILE" << 'EOF'
# Routing Skill Test Results
## Test Execution
Running test cases against the routing skill...
EOF
echo "Test harness created. Running manual evaluation..."
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment