--- name: nextjs description: Next.js development best practices and patterns. App router, server components, API routes, and deployment. Use when user mentions "nextjs", "next.js", "react server", "app router", "next deployment". author: Descomplicar® Crescimento Digital version: 2.0.0 quality_score: 75 user_invocable: true allowed-tools: Glob --- # /nextjs - Next.js Development Desenvolvimento Next.js moderno (13+) com App Router e Server Components. ## Quando Usar - Criar aplicações Next.js - Migrar de Pages para App Router - Implementar Server Components - Configurar Server Actions - Optimizar SEO e performance ## App Router Structure ``` app/ ├── layout.tsx # Root layout (obrigatório) ├── page.tsx # Home page ├── loading.tsx # Loading UI (Suspense) ├── error.tsx # Error boundary ├── not-found.tsx # 404 page ├── globals.css # Global styles ├── (auth)/ # Route group (não afecta URL) │ ├── login/page.tsx │ └── register/page.tsx ├── dashboard/ │ ├── layout.tsx # Nested layout │ ├── page.tsx │ └── [id]/ │ └── page.tsx # Dynamic route └── api/ └── route.ts # API route ``` ## Server vs Client Components ### Server Component (default) ```tsx // ✅ PADRÃO - Runs on server async function ProductsPage() { // Pode fazer fetch directo const products = await db.product.findMany(); return (
{products.map(p => ( ))}
); } export default ProductsPage; ``` **Vantagens:** - Acesso directo a BD - Menos JavaScript no cliente - SEO melhor - Dados sempre frescos ### Client Component ```tsx 'use client'; import { useState } from 'react'; // ✅ Para interactividade function Counter() { const [count, setCount] = useState(0); return ( ); } ``` **Quando usar:** - useState, useEffect, useContext - Event listeners (onClick, onChange) - Browser APIs (localStorage, window) - Custom hooks ## Data Fetching Patterns ### 1. Static (SSG) ```tsx // Default behaviour - cache infinito async function Page() { const data = await fetch('https://api.example.com/data', { cache: 'force-cache' // Explícito (mas é default) }); return
{data.title}
; } ``` ### 2. Dynamic (SSR) ```tsx // Sempre fetch fresco async function Page() { const data = await fetch('https://api.example.com/data', { cache: 'no-store' // NUNCA cache }); return
{data.title}
; } ``` ### 3. Revalidate (ISR) ```tsx // Cache com revalidação automática async function Page() { const data = await fetch('https://api.example.com/data', { next: { revalidate: 60 } // Revalida a cada 60s }); return
{data.title}
; } ``` ## Server Actions ```tsx // app/actions.ts 'use server'; import { revalidatePath } from 'next/cache'; import { db } from '@/lib/db'; export async function createPost(formData: FormData) { const title = formData.get('title') as string; const content = formData.get('content') as string; await db.post.create({ data: { title, content } }); revalidatePath('/posts'); } // app/create-post/page.tsx import { createPost } from '@/app/actions'; export default function CreatePost() { return (