Next.js Optimization Recipes
Next.js App Router changed the mental model for React applications. Server Components, streaming, parallel routes, intercepting routes — the surface area is huge and AI tools sometimes generate Pages Router patterns by mistake. These recipes produce App Router code exclusively, with correct server/client boundaries and proper data patterns.
What You Will Walk Away With
Section titled “What You Will Walk Away With”- Server Component and Server Action recipes with correct boundaries
- Data fetching patterns using RSC, streaming, and Suspense
- Authentication and middleware recipes for App Router
- Performance optimization prompts for Core Web Vitals
Recipe 1: Streaming with Independent Suspense Boundaries
Section titled “Recipe 1: Streaming with Independent Suspense Boundaries”Scenario: Your dashboard page makes 4 independent API calls. They all block rendering until the slowest one resolves.
Expected output: Page with 4 Suspense boundaries, 4 async section components, 4 skeletons, and metadata.
Recipe 2: Server Actions for Form Handling
Section titled “Recipe 2: Server Actions for Form Handling”Scenario: You need a contact form that validates server-side, handles errors, and shows pending state without a separate API route.
Expected output: Server action, page component, client form component, and tests.
Recipe 3: Authentication with NextAuth.js v5
Section titled “Recipe 3: Authentication with NextAuth.js v5”Scenario: You need email/password and OAuth authentication with session management and protected routes.
A NextAuth scaffold spans auth.ts, middleware.ts, the [...nextauth] route handler, the client wrapper, and components — the server/client boundary is where AI tools slip up most, so pick the workflow that lets you police it.
Use agent mode to scaffold auth.ts, middleware.ts, and the route handler together, then checkpoint before accepting. Auth is the classic case where the AI sprinkles "use client" onto a Server Component and silently kills SSR — the inline diff lets you catch the wrong directive before it ships.
Generate the whole auth surface in one headless pass, then guard the boundary with a hook: add a PostToolUse hook on *.tsx that greps for "use client" co-located with a generateMetadata or auth() server call and fails the edit. Run claude -p "set up NextAuth v5 per auth.ts and protect /dashboard via middleware" so the middleware matcher and callbacks land in a single turn.
Develop auth in a worktree so the half-finished middleware.ts never breaks your running dev branch, then push and let the Cloud reviewer check the protected-route matcher and JWT callback exposure before merge — session/role leaks are exactly what a fresh review pass catches.
Expected output: Auth config, middleware, route handler, client utilities, components, HOC, and tests.
Recipe 4: Parallel and Intercepting Routes for Modals
Section titled “Recipe 4: Parallel and Intercepting Routes for Modals”Scenario: Product details should open in a modal from the list but show a full page when accessed directly.
Expected output: Product pages, intercepting route, layout with parallel slots, modal component, and tests.
Recipe 5: Edge API Route Handlers
Section titled “Recipe 5: Edge API Route Handlers”Scenario: You need low-latency API routes running on the edge with typing, validation, and caching.
Expected output: Route handlers, API utility library, and tests for each endpoint.
Recipe 6: Incremental Static Regeneration for Blog
Section titled “Recipe 6: Incremental Static Regeneration for Blog”Scenario: Your blog has 500 posts. Full static generation takes 10 minutes. You need ISR.
Expected output: Blog pages with ISR, revalidation webhook, sitemap, OG image generation, and tests.
Recipe 7: Edge Middleware for A/B Testing and Feature Flags
Section titled “Recipe 7: Edge Middleware for A/B Testing and Feature Flags”Scenario: Split traffic between landing page variants and gate features behind flags at the edge.
Expected output: Middleware, utility functions, variant directories, and tests.
Recipe 8: Dynamic Metadata and Structured Data System
Section titled “Recipe 8: Dynamic Metadata and Structured Data System”Scenario: Every page needs unique meta tags, dynamic OG images, and JSON-LD structured data.
Expected output: Metadata utility, OG image generation, JSON-LD helpers, robots.ts, sitemap.ts, and tests.
Recipe 9: Core Web Vitals Optimization
Section titled “Recipe 9: Core Web Vitals Optimization”Scenario: Lighthouse performance score is 65. LCP 4.2s, CLS 0.25, INP 320ms.
Vitals work splits cleanly into two halves: scattered component edits (images, fonts, dynamic imports) and a CI budget gate. Different tools own each half better.
Use agent mode to sweep the component edits — next/image conversions, next/font swaps, useDeferredValue on the filter — across many files at once, watching the inline diffs so a priority prop does not land on every image. Cursor’s visual review is fastest for this kind of broad, repetitive change.
Best fit for the CI half: have it write the Lighthouse CI GitHub Action with hard budgets (LCP < 2.5s, CLS < 0.1, INP < 200ms) and wire web-vitals reporting headless. The terminal flow makes it trivial to run the Lighthouse pass locally and feed the failing audit JSON straight back into the next prompt.
Run the optimization as a Cloud task that opens a PR, so the before/after Lighthouse numbers and the new CI workflow get reviewed together. A worktree keeps the perf branch separate while the budgets settle.
Expected output: Optimized components, config changes, font setup, Lighthouse CI workflow, and metrics.
Recipe 10: Multi-Tenant SaaS Architecture
Section titled “Recipe 10: Multi-Tenant SaaS Architecture”Scenario: Your SaaS serves multiple tenants from a single deployment with subdomain-based routing and data isolation.
Expected output: Middleware, tenant utility, provider, scoped queries, themed layout, and isolation tests.
Recipe 11: Plugin Architecture for Extensible Dashboards
Section titled “Recipe 11: Plugin Architecture for Extensible Dashboards”Scenario: Your dashboard needs user-installed plugins that add pages, API routes, and UI components.
Expected output: Plugin interface, registry, catch-all routes, sidebar integration, installation flow, and tests.
Recipe 12: End-to-End Type Safety with tRPC
Section titled “Recipe 12: End-to-End Type Safety with tRPC”Scenario: Your 20 API endpoints have types that are always out of sync with the frontend.
tRPC’s payoff is end-to-end type inference, so the real test of any tool here is whether a change to a router output surfaces as a compile error on the client — not whether the files were generated.
Scaffold server/trpc.ts, the routers, and the client wiring in agent mode, then prove the loop interactively: change a procedure’s return type and watch the red squiggle appear in the consuming component. The live type-checking in the editor is the fastest way to confirm inference is actually wired through.
Generate the full tRPC setup headless, then encode the contract as a check: add a PostToolUse hook running tsc --noEmit so any drift between a router and its useQuery call fails immediately. Ask it to add a deliberately-breaking test (claude -p "change posts.list output and confirm the component fails to typecheck") to lock the guarantee in.
Use a worktree to build the router layer in isolation, then push and let the Cloud reviewer confirm every procedure has Zod input validation and the isAuthed/isAdmin middleware is applied where it should be — the cross-cutting auth checks are easy to miss in a 20-endpoint diff.
Expected output: tRPC setup, routers, handler, typed client, React Query integration, and type-safety verification.
When Recipes Break
Section titled “When Recipes Break”What Is Next
Section titled “What Is Next”- React patterns for component-level recipes inside Next.js
- API patterns for standalone API design
- Docker patterns for containerizing your Next.js app