/frontend-design:nextjs-patternsfrom frontend-design
Production-grade Next.js App Router patterns covering rendering (RSC, PPR, Cache Components), data fetching, mutations, auth, state, performance, security, testing, and deployment.
Ships in frontend-design. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub theviziusgroup/vibe-engineering-skills --plugin frontend-designDefault to the server, opt into the client at the leaves. Keep Server Components as the default; push 'use client' to the smallest interactive leaf; fetch data on the server (parallelized with Promise.all); stream with Suspense; treat every Server Action and Route Handler as a public, unauthenticated endpoint that must independently validate input (Zod) and re-check authorization.
| Version | Released | Key change |
|---|---|---|
| v14 | — | fetch cached by default; experimental PPR |
| v15 | Oct 21, 2024 | fetch uncached by default; cache opt-in required |
| v16 | Oct 21, 2025 | Cache Components stable (cacheComponents: true, use cache); PPR is now default behavior when enabled; React Compiler 1.0 stable but opt-in; middleware.ts renamed to proxy.ts (Node.js runtime) |
This is the #1 source of cache bugs. Before debugging caching issues, always identify which major version the codebase is on.
app/ is for Routing OnlyKeep page.tsx/layout.tsx thin. Move logic into a feature/domain structure:
src/
app/ # routing only — thin page/layout files
features/ # domain logic: auth/, products/, checkout/
server/ # DAL, DB queries, service functions
lib/ # shared pure utilities
components/ # genuinely shared UI
Why not layer-based buckets (components/, hooks/, utils/)? They read well early but degrade into high-fan-in dependency magnets at scale. Feature-based structure keeps a feature's code together and makes it testable and deletable.
Folders in app/ are not routable until a page/route file exists. Safely colocate components, tests, and utilities inside route segments.
_folderName — private folder excluded from routing(groupName) — route group: organizes without affecting URL; enables multiple root layoutsEstablish a DAL from day one — a service/repository layer that:
Putting business logic directly in Server Actions makes it untestable; extract pure service functions.
Turborepo is the default (maintained by Vercel). Critical configuration:
outputs in turbo.json or every task rebuilds from scratchtranspilePackages for internal packagesoutput: 'standalone' + correct outputFileTracingRoot for deploying a single appBarrel exports: Large index.ts barrels hurt dev compile time and tree-shaking. experimental.optimizePackageImports auto-rewrites named imports for known libraries (lucide-react, @mui/material) — but does NOT reliably work for internal workspace packages with Turbopack/symlinks (pnpm). For your own barrel files, refactor to direct imports.
Use Server Components (default) for:
Use Client Components ('use client') only for:
onClick, useState, useEffect)window, localStorage, navigator)Common mistakes:
'use client' high in the tree — promotes whole subtree, ships unnecessary JS, kills streaming/SEOcookies()/headers() in layouts — forces the whole route dynamic, disables static/PPRuseEffect instead of server fetch — delays render, hurts LCP/SEO, creates waterfallsTo avoid promoting whole subtrees to the client, pass Server Components as children:
// DO: server component renders and passes as children prop
<ClientWrapper>{/* server component here */}</ClientWrapper>
// DON'T: importing a server component inside a client component
// (silently promotes it to client)
Layouts: Cannot pass data to children via props. Each segment that needs data fetches it independently — fetch memoization makes this cheap.
Parallel routes (@slot): Render multiple independent segments in one layout. Real uses:
default.tsx for hard navigations or the app errorsIntercepting routes ((.), (..), (...)): Combined with parallel routes, the canonical use is modals with shareable URLs — Instagram-style photo overlays, login modals with a standalone /login page. Known gotchas:
(..) counts route segments, not filesystem levels (@slot folders are skipped)loading.tsx auto-wraps a route in Suspense with the file's content as fallbackerror.tsx must be a Client Component:
'use client'
export default function Error({ error, reset }: { error: Error; reset: () => void }) { ... }
global-error.tsx is the root fallback — must render its own <html> and <body>, and cannot use providers above it.
In v15+, fetch is uncached by default. To cache:
fetch(url, { cache: 'force-cache' }) — permanent until revalidatedfetch(url, { next: { revalidate: 60 } }) — time-based ISRexport const revalidate = 60 — segment-level time-basedInvalidation strategies:
revalidatePath('/path') — invalidate all data behind a URL (start here, easier to reason about)revalidateTag('tag') — fine-grained, invalidates data behind multiple URLs sharing a tagIn v16 Cache Components (use cache):
use cache directive + cacheLife() + cacheTag() extends tagging beyond fetch to any async work (DB queries, filesystem reads)updateTag() is Server-Action-only for read-your-own-writes// BAD: sequential — each waits for the previous
const user = await getUser(id)
const posts = await getPosts(id)
// GOOD: parallel — both fire at once
const [user, posts] = await Promise.all([getUser(id), getPosts(id)])
// Use Promise.allSettled for partial-failure tolerance
Preload pattern — start a fetch early before a blocking call:
void preloadItem(id) // fire-and-forget, starts fetching immediately
const critical = await getCriticalData()
import { cache } from 'react'
export const getUser = cache(async (id: string) => {
return db.user.findUnique({ where: { id } })
})
// Called anywhere in the render tree — executes only once per request
Use the server-only package to prevent accidental client import of DB-touching functions.
Still valuable for: client-side caching, optimistic updates, polling/real-time, and direct cache manipulation. Pattern: fetch initial data on the server, hydrate, then use TanStack Query client-side for live updates.
Server Actions compile to public POST endpoints. Built-in protections: Origin/Host comparison, POST-only, encrypted non-deterministic action IDs, dead-code elimination.
You still must:
safeParse, never parse)import { createSafeActionClient } from 'next-safe-action'
import { z } from 'zod'
const action = createSafeActionClient()
.inputSchema(z.object({ id: z.string().cuid() }))
.action(async ({ parsedInput, ctx }) => {
// input is already validated; ctx has auth from .use() middleware
return await updateItem(parsedInput.id)
})
next-safe-action provides: composable .use() middleware (auth, rate-limit), useAction/useOptimisticAction hooks, Standard Schema support (Zod, Valibot, ArkType). zsa is an alternative.
useActionState — wraps a Server Action with state (pending, error, data)useFormStatus — gives pending state to submit buttons inside a formuseOptimistic — instant UI feedback while action confirms| State type | Best tool |
|---|---|
| URL/shareable (filters, pagination, search) | nuqs (parseAsInteger, parseAsArrayOf) |
| Server state | Keep on server; React cache() + Server Components |
| Global client UI state | Zustand (single store) or Jotai (atomic/derived) |
| Form state | react-hook-form + zodResolver |
| Context (theme, locale) | React Context in a Client Component provider |
Critical App Router rule: Never create a global store at module level on the server — it leaks state across requests. Create per-request stores via provider patterns.
limitUrlUpdatesContext providers must be Client Components, don't cross the server/client boundary, and re-render all consumers (performance trap). Use for low-frequency values only.
Single auth.ts config exports { auth, handlers, signIn, signOut }. Universal auth() works in Server Components, Route Handlers, and middleware.
Split config for edge compatibility:
auth.config.ts — edge-safe, no DB adapter; used in middleware for JWT verificationauth.ts — Node.js runtime, with DB adapter for session storage| Strategy | Pros | Cons |
|---|---|---|
| JWT | Stateless, edge-verifiable, fast | Hard to revoke |
| Database | Revocable, single source of truth | DB call per request; edge can't reach most DBs |
Common middle ground: short-lived JWT (~15 min) + refresh token in DB.
Always store session tokens in httpOnly, secure, sameSite cookies — never localStorage (XSS).
UI role checks are UX, not security. Include API routes in the middleware matcher (common bug: protecting /dashboard but leaving /api/dashboard/* open).
TypeScript types are erased at runtime. userId: string does not stop {"userId": {"$ne": null}}.
const schema = z.object({ userId: z.string().cuid() })
const result = schema.safeParse(input)
if (!result.success) return { error: result.error.flatten().fieldErrors }
const { userId } = result.data
Validate every Server Action and Route Handler input. Infer types with z.infer<typeof schema>.
Enable typedRoutes in next.config.ts to catch invalid <Link href> at compile time.
Choose tRPC (T3 stack) when you want end-to-end typed RPC across a separate client. tRPC v11 (2025) integrates with RSC — call procedures directly in Server Components. create-t3-app scaffolds App Router by default.
| Layer | Tool | Notes |
|---|---|---|
| Unit (sync Server/Client Components, Server Actions as plain functions, Zod schemas) | Vitest + React Testing Library | Vitest cannot render async Server Components — push those to E2E |
| E2E (async RSC, auth flows, checkout, cookies/middleware) | Playwright | Configure webServer; preferred over Cypress |
| Mocking | Vitest mocks for next/navigation, next/headers | Mocky Balboa for server-side network mocking in Playwright |
| Approach | RSC-compatible | Runtime cost | Notes |
|---|---|---|---|
| Tailwind CSS | Yes | Zero | Default for new App Router projects; foundation for shadcn/ui |
| CSS Modules | Yes | Zero | Built-in, scoped, zero-config |
| vanilla-extract / Panda CSS / StyleX | Yes | Zero | Zero-runtime CSS-in-JS |
| styled-components / Emotion | No (requires 'use client' boundary and registry) | Runtime | Inherent perf trade-offs in App Router |
Migration advice: Don't rip out a working styled-components codebase wholesale. Adopt Tailwind for new components, or move to zero-runtime. Dark mode: next-themes with class-based Tailwind dark:.
| Tool | What it does | Critical detail |
|---|---|---|
next/image | Automatic WebP/AVIF, lazy loading, responsive srcset | Set priority on LCP image; always provide width/height |
next/font | Self-hosts fonts at build time; zero runtime network request | Eliminates layout shift + external DNS; display: 'swap' built-in |
next/script | Controls third-party script loading strategy | afterInteractive, lazyOnload, experimental worker |
next/dynamic | Code splitting for heavy components | ssr: false for client-only libs |
@next/bundle-analyzer | Visualize bundle composition | Run with ANALYZE=true; set CI size budgets |
Common bundle culprits: moment.js (→ date-fns/dayjs), full lodash (→ lodash-es or per-method), full icon libraries (→ optimizePackageImports).
Mental model: everything outside <Suspense> is static, everything inside is dynamic. The static shell is served from the edge (TTFB ~40–90ms), dynamic holes stream in one HTTP response.
Best for: Pages with a stable shell and small dynamic regions (product pages, pricing, marketing surfaces with ~80% cacheable layout, ~20% per-user data).
Skip PPR for: 100%-personalized pages (account settings, live dashboards), fully authenticated apps (generic shell has little CDN value).
Debugging: a single cookies()/headers()/connection() call outside Suspense makes the route fully dynamic. Use NEXT_LOG_LEVEL=debug next build to print why a route is dynamic.
The x-middleware-subrequest header could bypass all middleware-based authorization. Published March 21, 2025; reported by Rachid Allam.
next start)Published May 6–7, 2026 — covering auth bypass, SSRF, cache poisoning, XSS, RSC denial-of-service (CVE-2026-23870).
@upstash/ratelimit + Upstash Redis (sliding window) is the dominant pattern.
Key rules:
returnTo/redirect params to relative URLs only (open-redirect/phishing prevention)NEXT_PUBLIC_ env vars (these are baked into the client bundle at build time)server-only package to prevent accidental client importtaintObjectReference, taintUniqueValue) to prevent passing sensitive objects to Client ComponentsNEXT_SERVER_ACTIONS_ENCRYPTION_KEY for consistent keys across instances| Factor | Vercel | Self-hosted (Docker/K8s) |
|---|---|---|
| Setup | Zero-config | You own CI/CD, cache warming, health probes |
| ISR | Distributed automatically | Cache lives in .next/cache, not durable without custom cache handler |
| Image optimization | Automatic | Requires sharp installed |
| Version skew protection | Built-in | Manual |
| Cost | Significant above ~10M requests/month | Predictable |
# output: 'standalone' traces exact deps into a minimal Node server
# Copy public/ and .next/static separately
Critical self-hosting checklist:
proxy_buffering off, X-Accel-Buffering no, HTTP/1.1NEXT_PUBLIC_ vars are build-time — need rebuild or separate images per environmentNEXT_SERVER_ACTIONS_ENCRYPTION_KEY for multi-instance consistencyoutput: 'standalone' — minimal Node server (~200MB image vs 1GB+); required for clean Docker/K8soutput: 'export' — fully static (replaces old next export)| Anti-pattern | Why it's wrong |
|---|---|
Over-using 'use client' | Promotes subtrees, bloats bundles, breaks streaming/SEO |
useEffect for data that could be server-fetched | Delays render, hurts LCP/SEO, creates waterfalls |
Reading cookies()/headers() in layouts | Forces entire route dynamic, disables static/PPR |
| N+1 queries | Fetch in a loop; batch with Promise.all/DataLoader |
| Trusting page-level auth for Server Actions | Actions are separate public endpoints; re-verify each time |
| Trusting TypeScript types at runtime | Always validate with Zod |
| Module-level global stores on the server | Leaks state across requests |
Fine-grained revalidatePath on everything | Over-invalidation busts unrelated caches; use tags |
| Assuming v14 caching in a v15/v16 codebase | fetch is no longer cached by default |
Stage 1 — Foundation (any new project):
create-next-app (or create-t3-app for typed RPC + Prisma/Drizzle + Auth.js) on App Router, src/ directory, TypeScript strict, Tailwind, ESLint. Feature-based structure from day one; establish a DAL.
Stage 2 — Data and mutations:
Server Actions with next-safe-action + Zod; react-hook-form + zodResolver on client; useActionState/useOptimistic for UX. Decide caching explicitly.
Stage 3 — Auth and security hardening (before launch):
Auth.js v5 with split edge/Node config; JWT + DB refresh token. Verify auth in middleware AND DAL AND every Server Action. Add @upstash/ratelimit to auth and expensive endpoints. Pin Next.js to a patched version.
Stage 4 — Performance and scale:
next/image, next/font, next/script, next/dynamic; bundle analysis with CI budgets; PPR/Cache Components for mixed static+dynamic pages. Target: LCP <2.5s, INP <200ms, CLS <0.1.
Stage 5 — Deployment decision: Default Vercel for time-to-market. Re-evaluate self-hosting at ~10M+ requests/month, compliance/data-residency needs, or existing K8s platform.
3 skills in this plugin
/graphic-ux-ui-designComprehensive UX/UI and graphic design reference covering visual design fundamentals (color systems, typography, dark mode, layout), component and interaction patterns (navigation, forms, buttons, modals, loading states), accessibility standards (WCAG 2.2, APCA, screen readers), UX research methods, and design systems (token architecture, Atomic Design, governance, versioning). Use when designing interfaces, auditing accessibility, building or evaluating design systems, choosing component patterns, or applying evidence-based UX decisions./performance-optimizationProduction performance reference covering Python (profiling with py-spy/Scalene, GIL and free-threading in 3.13t/3.14t, NumPy/Pandas vectorization 100–740x wins, Numba/Cython/PyPy, asyncio best practices, ASGI vs WSGI), Next.js/TypeScript (Core Web Vitals, RSC bundle discipline, PPR/Cache Components, App Router caching layers, Turbopack, DB pooling), and Azure cloud (compute cold starts, ACA/KEDA scale-to-zero, messaging service selection, Cosmos DB vs PostgreSQL, Redis ConnectionMultiplexer, Front Door CDN/WAF, VMSS autoscale, cost tiers). Use when diagnosing or fixing performance bottlenecks in Python services, Next.js apps, or Azure infrastructure.2 plugins ship this exact skill · first indexed Aug 12, 2026
Other plugins' skills for the same job