556
Bn
bees-nest / files
bees-nest / .opencode / skills / nextjs-app-router-patterns / SKILL.md
13.3 KB
1--- 2name: nextjs-app-router-patterns 3description: Master Next.js 14+ App Router with Server Components, streaming, parallel routes, and advanced data fetching. Use when building Next.js applications, implementing SSR/SSG, or optimizing React Server Components. 4--- 5 6# Next.js App Router Patterns 7 8Comprehensive patterns for Next.js 14+ App Router architecture, Server Components, and modern full-stack React development. 9 10## When to Use This Skill 11 12- Building new Next.js applications with App Router 13- Migrating from Pages Router to App Router 14- Implementing Server Components and streaming 15- Setting up parallel and intercepting routes 16- Optimizing data fetching and caching 17- Building full-stack features with Server Actions 18 19## Core Concepts 20 21### 1. Rendering Modes 22 23| Mode | Where | When to Use | 24| --------------------- | ------------ | ----------------------------------------- | 25| **Server Components** | Server only | Data fetching, heavy computation, secrets | 26| **Client Components** | Browser | Interactivity, hooks, browser APIs | 27| **Static** | Build time | Content that rarely changes | 28| **Dynamic** | Request time | Personalized or real-time data | 29| **Streaming** | Progressive | Large pages, slow data sources | 30 31### 2. File Conventions 32 33``` 34app/ 35├── layout.tsx # Shared UI wrapper 36├── page.tsx # Route UI 37├── loading.tsx # Loading UI (Suspense) 38├── error.tsx # Error boundary 39├── not-found.tsx # 404 UI 40├── route.ts # API endpoint 41├── template.tsx # Re-mounted layout 42├── default.tsx # Parallel route fallback 43└── opengraph-image.tsx # OG image generation 44``` 45 46## Quick Start 47 48```typescript 49// app/layout.tsx 50import { Inter } from 'next/font/google' 51import { Providers } from './providers' 52 53const inter = Inter({ subsets: ['latin'] }) 54 55export const metadata = { 56 title: { default: 'My App', template: '%s | My App' }, 57 description: 'Built with Next.js App Router', 58} 59 60export default function RootLayout({ 61 children, 62}: { 63 children: React.ReactNode 64}) { 65 return ( 66 <html lang="en" suppressHydrationWarning> 67 <body className={inter.className}> 68 <Providers>{children}</Providers> 69 </body> 70 </html> 71 ) 72} 73 74// app/page.tsx - Server Component by default 75async function getProducts() { 76 const res = await fetch('https://api.example.com/products', { 77 next: { revalidate: 3600 }, // ISR: revalidate every hour 78 }) 79 return res.json() 80} 81 82export default async function HomePage() { 83 const products = await getProducts() 84 85 return ( 86 <main> 87 <h1>Products</h1> 88 <ProductGrid products={products} /> 89 </main> 90 ) 91} 92``` 93 94## Patterns 95 96### Pattern 1: Server Components with Data Fetching 97 98```typescript 99// app/products/page.tsx 100import { Suspense } from 'react' 101import { ProductList, ProductListSkeleton } from '@/components/products' 102import { FilterSidebar } from '@/components/filters' 103 104interface SearchParams { 105 category?: string 106 sort?: 'price' | 'name' | 'date' 107 page?: string 108} 109 110export default async function ProductsPage({ 111 searchParams, 112}: { 113 searchParams: Promise<SearchParams> 114}) { 115 const params = await searchParams 116 117 return ( 118 <div className="flex gap-8"> 119 <FilterSidebar /> 120 <Suspense 121 key={JSON.stringify(params)} 122 fallback={<ProductListSkeleton />} 123 > 124 <ProductList 125 category={params.category} 126 sort={params.sort} 127 page={Number(params.page) || 1} 128 /> 129 </Suspense> 130 </div> 131 ) 132} 133 134// components/products/ProductList.tsx - Server Component 135async function getProducts(filters: ProductFilters) { 136 const res = await fetch( 137 `${process.env.API_URL}/products?${new URLSearchParams(filters)}`, 138 { next: { tags: ['products'] } } 139 ) 140 if (!res.ok) throw new Error('Failed to fetch products') 141 return res.json() 142} 143 144export async function ProductList({ category, sort, page }: ProductFilters) { 145 const { products, totalPages } = await getProducts({ category, sort, page }) 146 147 return ( 148 <div> 149 <div className="grid grid-cols-3 gap-4"> 150 {products.map((product) => ( 151 <ProductCard key={product.id} product={product} /> 152 ))} 153 </div> 154 <Pagination currentPage={page} totalPages={totalPages} /> 155 </div> 156 ) 157} 158``` 159 160### Pattern 2: Client Components with 'use client' 161 162```typescript 163// components/products/AddToCartButton.tsx 164'use client' 165 166import { useState, useTransition } from 'react' 167import { addToCart } from '@/app/actions/cart' 168 169export function AddToCartButton({ productId }: { productId: string }) { 170 const [isPending, startTransition] = useTransition() 171 const [error, setError] = useState<string | null>(null) 172 173 const handleClick = () => { 174 setError(null) 175 startTransition(async () => { 176 const result = await addToCart(productId) 177 if (result.error) { 178 setError(result.error) 179 } 180 }) 181 } 182 183 return ( 184 <div> 185 <button 186 onClick={handleClick} 187 disabled={isPending} 188 className="btn-primary" 189 > 190 {isPending ? 'Adding...' : 'Add to Cart'} 191 </button> 192 {error && <p className="text-red-500 text-sm">{error}</p>} 193 </div> 194 ) 195} 196``` 197 198### Pattern 3: Server Actions 199 200```typescript 201// app/actions/cart.ts 202"use server"; 203 204import { revalidateTag } from "next/cache"; 205import { cookies } from "next/headers"; 206import { redirect } from "next/navigation"; 207 208export async function addToCart(productId: string) { 209 const cookieStore = await cookies(); 210 const sessionId = cookieStore.get("session")?.value; 211 212 if (!sessionId) { 213 redirect("/login"); 214 } 215 216 try { 217 await db.cart.upsert({ 218 where: { sessionId_productId: { sessionId, productId } }, 219 update: { quantity: { increment: 1 } }, 220 create: { sessionId, productId, quantity: 1 }, 221 }); 222 223 revalidateTag("cart"); 224 return { success: true }; 225 } catch (error) { 226 return { error: "Failed to add item to cart" }; 227 } 228} 229 230export async function checkout(formData: FormData) { 231 const address = formData.get("address") as string; 232 const payment = formData.get("payment") as string; 233 234 // Validate 235 if (!address || !payment) { 236 return { error: "Missing required fields" }; 237 } 238 239 // Process order 240 const order = await processOrder({ address, payment }); 241 242 // Redirect to confirmation 243 redirect(`/orders/${order.id}/confirmation`); 244} 245``` 246 247### Pattern 4: Parallel Routes 248 249```typescript 250// app/dashboard/layout.tsx 251export default function DashboardLayout({ 252 children, 253 analytics, 254 team, 255}: { 256 children: React.ReactNode 257 analytics: React.ReactNode 258 team: React.ReactNode 259}) { 260 return ( 261 <div className="dashboard-grid"> 262 <main>{children}</main> 263 <aside className="analytics-panel">{analytics}</aside> 264 <aside className="team-panel">{team}</aside> 265 </div> 266 ) 267} 268 269// app/dashboard/@analytics/page.tsx 270export default async function AnalyticsSlot() { 271 const stats = await getAnalytics() 272 return <AnalyticsChart data={stats} /> 273} 274 275// app/dashboard/@analytics/loading.tsx 276export default function AnalyticsLoading() { 277 return <ChartSkeleton /> 278} 279 280// app/dashboard/@team/page.tsx 281export default async function TeamSlot() { 282 const members = await getTeamMembers() 283 return <TeamList members={members} /> 284} 285``` 286 287### Pattern 5: Intercepting Routes (Modal Pattern) 288 289```typescript 290// File structure for photo modal 291// app/ 292// ├── @modal/ 293// │ ├── (.)photos/[id]/page.tsx # Intercept 294// │ └── default.tsx 295// ├── photos/ 296// │ └── [id]/page.tsx # Full page 297// └── layout.tsx 298 299// app/@modal/(.)photos/[id]/page.tsx 300import { Modal } from '@/components/Modal' 301import { PhotoDetail } from '@/components/PhotoDetail' 302 303export default async function PhotoModal({ 304 params, 305}: { 306 params: Promise<{ id: string }> 307}) { 308 const { id } = await params 309 const photo = await getPhoto(id) 310 311 return ( 312 <Modal> 313 <PhotoDetail photo={photo} /> 314 </Modal> 315 ) 316} 317 318// app/photos/[id]/page.tsx - Full page version 319export default async function PhotoPage({ 320 params, 321}: { 322 params: Promise<{ id: string }> 323}) { 324 const { id } = await params 325 const photo = await getPhoto(id) 326 327 return ( 328 <div className="photo-page"> 329 <PhotoDetail photo={photo} /> 330 <RelatedPhotos photoId={id} /> 331 </div> 332 ) 333} 334 335// app/layout.tsx 336export default function RootLayout({ 337 children, 338 modal, 339}: { 340 children: React.ReactNode 341 modal: React.ReactNode 342}) { 343 return ( 344 <html> 345 <body> 346 {children} 347 {modal} 348 </body> 349 </html> 350 ) 351} 352``` 353 354### Pattern 6: Streaming with Suspense 355 356```typescript 357// app/product/[id]/page.tsx 358import { Suspense } from 'react' 359 360export default async function ProductPage({ 361 params, 362}: { 363 params: Promise<{ id: string }> 364}) { 365 const { id } = await params 366 367 // This data loads first (blocking) 368 const product = await getProduct(id) 369 370 return ( 371 <div> 372 {/* Immediate render */} 373 <ProductHeader product={product} /> 374 375 {/* Stream in reviews */} 376 <Suspense fallback={<ReviewsSkeleton />}> 377 <Reviews productId={id} /> 378 </Suspense> 379 380 {/* Stream in recommendations */} 381 <Suspense fallback={<RecommendationsSkeleton />}> 382 <Recommendations productId={id} /> 383 </Suspense> 384 </div> 385 ) 386} 387 388// These components fetch their own data 389async function Reviews({ productId }: { productId: string }) { 390 const reviews = await getReviews(productId) // Slow API 391 return <ReviewList reviews={reviews} /> 392} 393 394async function Recommendations({ productId }: { productId: string }) { 395 const products = await getRecommendations(productId) // ML-based, slow 396 return <ProductCarousel products={products} /> 397} 398``` 399 400### Pattern 7: Route Handlers (API Routes) 401 402```typescript 403// app/api/products/route.ts 404import { NextRequest, NextResponse } from "next/server"; 405 406export async function GET(request: NextRequest) { 407 const searchParams = request.nextUrl.searchParams; 408 const category = searchParams.get("category"); 409 410 const products = await db.product.findMany({ 411 where: category ? { category } : undefined, 412 take: 20, 413 }); 414 415 return NextResponse.json(products); 416} 417 418export async function POST(request: NextRequest) { 419 const body = await request.json(); 420 421 const product = await db.product.create({ 422 data: body, 423 }); 424 425 return NextResponse.json(product, { status: 201 }); 426} 427 428// app/api/products/[id]/route.ts 429export async function GET( 430 request: NextRequest, 431 { params }: { params: Promise<{ id: string }> }, 432) { 433 const { id } = await params; 434 const product = await db.product.findUnique({ where: { id } }); 435 436 if (!product) { 437 return NextResponse.json({ error: "Product not found" }, { status: 404 }); 438 } 439 440 return NextResponse.json(product); 441} 442``` 443 444### Pattern 8: Metadata and SEO 445 446```typescript 447// app/products/[slug]/page.tsx 448import { Metadata } from 'next' 449import { notFound } from 'next/navigation' 450 451type Props = { 452 params: Promise<{ slug: string }> 453} 454 455export async function generateMetadata({ params }: Props): Promise<Metadata> { 456 const { slug } = await params 457 const product = await getProduct(slug) 458 459 if (!product) return {} 460 461 return { 462 title: product.name, 463 description: product.description, 464 openGraph: { 465 title: product.name, 466 description: product.description, 467 images: [{ url: product.image, width: 1200, height: 630 }], 468 }, 469 twitter: { 470 card: 'summary_large_image', 471 title: product.name, 472 description: product.description, 473 images: [product.image], 474 }, 475 } 476} 477 478export async function generateStaticParams() { 479 const products = await db.product.findMany({ select: { slug: true } }) 480 return products.map((p) => ({ slug: p.slug })) 481} 482 483export default async function ProductPage({ params }: Props) { 484 const { slug } = await params 485 const product = await getProduct(slug) 486 487 if (!product) notFound() 488 489 return <ProductDetail product={product} /> 490} 491``` 492 493## Caching Strategies 494 495### Data Cache 496 497```typescript 498// No cache (always fresh) 499fetch(url, { cache: "no-store" }); 500 501// Cache forever (static) 502fetch(url, { cache: "force-cache" }); 503 504// ISR - revalidate after 60 seconds 505fetch(url, { next: { revalidate: 60 } }); 506 507// Tag-based invalidation 508fetch(url, { next: { tags: ["products"] } }); 509 510// Invalidate via Server Action 511("use server"); 512import { revalidateTag, revalidatePath } from "next/cache"; 513 514export async function updateProduct(id: string, data: ProductData) { 515 await db.product.update({ where: { id }, data }); 516 revalidateTag("products"); 517 revalidatePath("/products"); 518} 519``` 520 521## Best Practices 522 523### Do's 524 525- **Start with Server Components** - Add 'use client' only when needed 526- **Colocate data fetching** - Fetch data where it's used 527- **Use Suspense boundaries** - Enable streaming for slow data 528- **Leverage parallel routes** - Independent loading states 529- **Use Server Actions** - For mutations with progressive enhancement 530 531### Don'ts 532 533- **Don't pass serializable data** - Server → Client boundary limitations 534- **Don't use hooks in Server Components** - No useState, useEffect 535- **Don't fetch in Client Components** - Use Server Components or React Query 536- **Don't over-nest layouts** - Each layout adds to the component tree 537- **Don't ignore loading states** - Always provide loading.tsx or Suspense 538 539## Resources 540 541- [Next.js App Router Documentation](https://nextjs.org/docs/app) 542- [Server Components RFC](https://github.com/reactjs/rfcs/blob/main/text/0188-server-components.md) 543- [Vercel Templates](https://vercel.com/templates/next.js)