Next.js Component & Skeleton Development (nextjs-component-dev)
Specialized workflow for creating production-ready React Server Components (RSC) and Client Components with Suspense skeletons, dual-layer TDD testing (Jest + RTL unit tests and Playwright integration/hydration/visual checks), next-intl dictionary-backed translations, semantic theme tokens, and live runtime diagnostics via next-devtools MCP.
[!TIP] Modular Assets & Templates:
- Next.js Docs Search & Context:
references/nextjs-docs-lookup.md- Testing Architecture & Verification:
references/testing-architecture-guide.md- Storybook Standards & Separation:
references/storybook-reference.md- Instant Navigation & Prefetching:
references/instant-navigation-and-prefetching.md- Next DevTools Debugging Guide:
references/next-devtools-debugging.md- Caching & Revalidation:
references/caching-and-revalidation.md- Code Templates:
resources/templates/(Component, Skeleton, Jest Unit Test, Playwright Spec)- Reference Implementations:
examples/- Verification Scripts:
scripts/verify-dev.ps1(Windows) /scripts/verify-dev.sh(Linux)
Architectural Rules & Standards
1. Planning Context & Paths
- Read
docs/project.jsonto resolvepackage_manager,new_component_dir,style_file_dir,component_library,dictionaries_dir(default:"messages"), andsupported_languages. - All internal routes MUST use
ROUTESfrom@/lib/routes. - All author/site metadata MUST use
SITE_CONFIGfrom@/lib/site-config. - Target path hierarchy:
<new_component_dir>/<page_or_global>/<ComponentName>/- Category:
global/for shared layout chrome;<page-name>/(e.g.home/,about/,lab/) for page-scoped sections.
- Category:
2. Next.js Internal Docs Lookup (node_modules/next/dist/docs)
- Search Local Docs via Codebase Memory MCP: For any component creation, actively query and inspect the local Next.js distribution docs at
node_modules/next/dist/docs/usingcodebase-memoryMCP tools (search_code,search_graph,get_code_snippet) for relevant API signatures, directives ('use cache','use client','use server'), built-in components (next/image,next/link,next/font,<Form>), navigation hooks (useRouter,usePathname), and caching policies (cacheLife,cacheTag). - Eliminate Deprecations & Hallucinations: Never rely on assumptions or outdated Next.js patterns; the local
node_modules/next/dist/docsmatching the installed package version is the primary source of truth. Consultreferences/nextjs-docs-lookup.md.
3. Dev Server & Next DevTools Protocol
- Dev Server Check & Tune-In: Before/during component development, check if the Next.js dev server is running via
next-devtoolsMCP server (nextjs_index). - If Server Running: Tune into the running server and port immediately; do not restart.
- If Server Not Running: Start the dev server in the background (
pnpm dev,IsDaemon: true) and verify connection vianextjs_index. - Runtime Debugging: After implementing components, query
next-devtools(nextjs_call) to inspect errors, check build status, and diagnose runtime issues immediately. Consultreferences/next-devtools-debugging.md.
4. RSC Boundaries & Leaf Client Push-Down
- Server Components by Default: Keep components server-rendered (
async function). - Push
"use client"Down: Isolate interactive handlers (buttons, toggles, form inputs) into small leaf Client Components. - RSC Composition: Pass Server Components as
childrenor props into Client wrappers. Never import Server Components inside"use client"files.
5. Styling, Logical Properties & Theme Tokens
- Semantic Tokens: Exclusively use semantic CSS variables defined in
app/globals.css(bg-background,text-foreground,border-border,text-muted-foreground). Hardcoded hex colors (#FAFAFA) or raw color scales (bg-blue-500) are FORBIDDEN. - Class Merging: Always merge classes using
cn(...)(clsx+tailwind-merge). - Logical Properties (BiDi): Exclusively use Tailwind logical properties (
ms-,pe-,ps-,me-,start,end). Physical directional classes (ml-,mr-,pl-,pr-,left-,right-) are FORBIDDEN. - Progress Links: Use
<Link>from@vercel/react-transition-progressfor primary navigation, hero CTAs, and interactive cards; use standardnext/linkfor static utility links. - Images: Always use
next/imagewith explicit dimensions orfill, responsivesizes, andpriorityfor above-the-fold LCP assets.
6. Instant Navigation, Granular Suspense & Caching Architecture
- The Three Levers for Instant Components:
- Push Down: Extract request-specific async operations (
await params,await searchParams,cookies(),headers(), uncached DB/API calls) into leaf sub-components wrapped in<Suspense>. Static parents and siblings lift directly into the static/App Shell. - Cache: Pair
'use cache'withcacheLifeandcacheTagat function/component level. Use Session Bridging patterns:- Pattern A (Extract & Pass): Extract session attributes (e.g.
team_id,role,tier) fromcookies()outside and pass as arguments to'use cache'functions so cached data is shared across all users with matching attributes (cost scales with team/attribute count, not user session count). - Pattern B (
"use cache: private"): For strictly user-specific session lookups, use browser-only session caching withstale >= 5mthat travels with the App Shell.
- Pattern A (Extract & Pass): Extract session attributes (e.g.
- Prefetching Strategy & Dense Grids:
- Default App Shell Prefetching (
<Link>/prefetch={null}): Prefetches one shared static/App Shell per route. Bounded cost ($O(\text{routes})$), zero server invocations per link. Use for dense feeds, card grids (50+ cards), and bulk navigation. - Per-Link Prefetching (
<Link prefetch={true}>): Resolves dynamic URL data (params,searchParams) before navigation with 1 server invocation per visible link. Use sparingly for high-intent primary CTAs, hero actions, or master-detail list items where skeleton flashing must be eliminated. - Dense Card Grids: NEVER use blanket
prefetch={true}across dozens of cards in feeds. Retain default<Link>or use hover/focus intent prefetching (router.prefetch()).
- Default App Shell Prefetching (
- Push Down: Extract request-specific async operations (
- Granular Loading States (Anti-Full-Page Flash): Never wrap an entire component or page in a single top-level
<Suspense>boundary that flashes full skeletons. Keep titles, layout frames, and cached content visible immediately; place<Suspense>strictly around dynamic streaming slots. - Native Next.js 16 Caching Directives: Consult
references/instant-navigation-and-prefetching.mdandreferences/caching-and-revalidation.md.
7. TanStack Query & Server Prefetching
- Unified Cache Contract: Define
key,tag, andqueryOptionswith explicitstaleTime(e.g.30_000ms). - Server Prefetch: Trigger unawaited prefetch (
void queryClient.prefetchQuery(...)) calling internal DB functions directly (zero relative fetch on server). Dehydrate with<HydrationBoundary>. - Streamed Components: Use
useSuspenseQueryinside<Suspense fallback={<[ComponentName]Skeleton />}>. - Optimistic Mutations: Use
useMutationwithonMutatecache snapshots andonErrorrollbacks; call Server Actions withupdateTag(cache.tag).
8. Dual-Layer Testing Division of Labor (Jest vs. Playwright)
- Jest + RTL (
[ComponentName].test.tsx):- Fast feedback loop in
jsdom. - Prop permutations, conditional UI elements, and empty/null states.
- User interactions via
@testing-library/user-event(neverfireEvent). - Next.js routing mocks (
useRouter,usePathname,useSearchParamsfromnext/navigation). next-intldictionary interpolation and pluralization checks insideNextIntlClientProvider.- Accessible role queries (
screen.getByRole) and automated a11y checks (jest-axe).
- Fast feedback loop in
- Playwright (
[ComponentName].spec.tsor page-level specs):- Real browser execution (Chromium/WebKit/Firefox).
- Instant Shell Assertions (
@next/playwright): Useinstant(page, ...)helper to assert that static shells and prefetched App Shells render immediately before dynamic server streaming resolves. - Zero-Hydration Mismatches: Listen to browser console events (
page.on('console')) to detect and fail tests on React SSR hydration warnings. - Visual & BiDi Regression: Use
expect(page).toHaveScreenshot()across themes (light vs. dark OKLCH variables) and text directions (dir="ltr"vs.dir="rtl"). - Network Resilience: Use
page.route()to test slow network responses (verifying Suspense skeletons match geometry to prevent CLS) and 500 error boundaries.
- Detailed Testing Standards: Consult
references/testing-architecture-guide.md.
Phase 0: Implementation Plan & Approval Gate
[!IMPORTANT] Plan Before Execution: Always generate and present an
implementation_plan.mdartifact detailing all planned file creations, modifications, TypeScript contracts, translation dictionary additions, and TDD test cases before executing any write operations, modifying dictionaries, or creating components in the repository. Wait for user confirmation/approval before proceeding with execution.
The implementation plan must cover:
- Target Architecture & Path: Full target directory (
<new_component_dir>/<page_or_global>/<ComponentName>/) and classification (RSC vs. Client leaf component). - Next.js Local Docs Consulted: Specific doc paths checked under
node_modules/next/dist/docs/(e.g.04-api-reference/04-components/image.md,03-directives/use-cache.md,04-api-reference/02-functions/use-router.md). - TypeScript Contracts: Prop interfaces and types with strict English TSDoc annotations.
- Dictionary Strategy: Explicit translation namespaces and keys to add to
messages/[locale].jsonacross allsupported_languagesindocs/project.json(zero hardcoded strings or in-file mock dictionaries). - Theme Tokens & Styling: Identified semantic OKLCH CSS variables and logical layout classes.
- Testing & Diagnostics Strategy:
- Jest Unit Tests (
[ComponentName].test.tsx): Mock configurations (next/navigation), prop variations, callback assertions,NextIntlClientProviderintegration, and a11y role queries. - Playwright Integration Scenarios (
[ComponentName].spec.ts): Visual snapshot targets (light/dark theme tokens, LTR vs. RTL logical layouts), network throttling/skeleton geometry checks, and hydration verification listeners. - Next DevTools Diagnostics: Runtime error and compilation checks via
next-devtools.
- Jest Unit Tests (
- Verification Gate: Exact verification commands to run (
verify-dev.ps1, targeted unit tests, and Playwright e2e specs).
Workflow Steps
-
Step 0: Implementation Plan Generation & Approval Gate
- Search and inspect
node_modules/next/dist/docsviacodebase-memoryMCP (search_code,search_graph) for any Next.js APIs, directives, hooks, or components utilized by the planned component to ensure up-to-date context. - Synthesize component requirements, scan
docs/project.json, and generateimplementation_plan.mddocumenting consulted docs and contracts. - Set
request_feedback = trueanduser_facing = trueon the artifact. - Wait for user review and explicit approval before writing any code.
- Search and inspect
-
Step 1: Dev Server Verification & Next DevTools Connection
- Query
next-devtoolsMCP vianextjs_indexto detect running Next.js dev server instances. - If Dev Server is running: Tune into the active port and server instance; continue developing without restarting.
- If Dev Server is NOT running: Start the dev server in the background (
pnpm dev,IsDaemon: true) and verify discovery withnextjs_index.
- Query
-
Step 2: Dictionary Population & TypeScript Contract Definition
- Read
docs/project.jsonto resolvedictionaries_dir(messagesis default) andsupported_languages. - Define the component's translation namespace and keys.
- Populate all dictionary files (
messages/en.json,messages/fa.json, etc.) with authentic translations for every supported language before writing JSX. - Define prop interfaces with strict English TSDoc annotations (
@param,@defaultValue,@returns). - If there are more than one supported language, component must fetch the translation first and if failed use fallbacks.
- Read
-
Step 3: TDD Baseline Unit Tests (
[ComponentName].test.tsxvia Jest + RTL)- Write
[ComponentName].test.tsxBEFORE implementing the component. - Mock
next/navigationhooks (useRouter,usePathname,useSearchParams). - Wrap rendered components in
NextIntlClientProvidersupplying the dictionarymessagesand activelocale. - Test directional attributes (
dir="rtl"vs.dir="ltr"), default props, interactive callbacks (@testing-library/user-event), Suspense skeleton fallbacks, and semantic ARIA roles.
- Write
-
Step 4: Component & Skeleton Implementation
- Create primary component
[ComponentName].tsx(RSC or Client Component) consuming translations vianext-intl(getTranslationsoruseTranslations) with zero hardcoded placeholders or in-file mock dictionary objects. - Create matching Suspense skeleton
[ComponentName]Skeleton.tsxmirroring layout geometry and classes to prevent CLS. - Create clean barrel export
index.ts.
- Create primary component
-
Step 5: Runtime Diagnostics & Verification Gate
- Next DevTools Runtime Inspection & Navigation Inspector: Use
next-devtoolsMCP server (nextjs_call) to check for compilation errors, runtime exceptions, hydration issues, or broken routes. Use Navigation Inspector ("Pause on navigations") to verify the static shell and App Shell render instantly with granular fallbacks. - Targeted Unit Test Execution: Run verification script to check companion files, dictionary compliance, and execute unit tests:
- Windows (PowerShell):
pwsh .agents/skills/nextjs-component-dev/scripts/verify-dev.ps1 -ComponentPath <target_component_dir> - Linux / macOS (Bash):
bash .agents/skills/nextjs-component-dev/scripts/verify-dev.sh <target_component_dir>
- Windows (PowerShell):
- Playwright Instant Navigation & Hydration Check: Run targeted Playwright component/integration spec:
pnpm test:e2e [ComponentName] - Validate that
instant()tests pass for hard page load and client navigation, visual snapshots pass across themes, and console listeners register 0 hydration mismatch errors. - Fix any syntax errors, missing dictionary keys, visual discrepancies, or test regressions until all assertions pass.
- Next DevTools Runtime Inspection & Navigation Inspector: Use
-
Step 6: Implementation Plan Checklist Synchronization
- Check off the completed component item (
- [x]) indocs/plan/05-pages-and-components.md. - If all sub-components and page infrastructure tasks for the parent page are completed, check off the parent page item (
- [x]).
- Check off the completed component item (
Edge Cases & AI Pitfalls
- Local Docs Verification via Codebase Memory MCP: Always search
node_modules/next/dist/docs/usingcodebase-memoryMCP tools (search_code,search_graph) before authoring components. Never assume deprecated Next.js API signatures or outdated caching mechanisms; local docs reflect the exact runtime version installed. - Zero In-File i18n Fallbacks: Never hardcode dictionary objects or fallbacks (
const DEFAULT_CONTENT = {...}) in TSX files. All text must come frommessages/[locale].json. - Hydration Warning Detection: Browser-only globals (
window,localStorage) accessed during SSR cause hydration mismatch crashes. Guard them behinduseEffector client checks. - Strict Logical Styling (BiDi): Never use physical directions (
ml-,mr-,pl-,pr-,left-,right-). Always use logical alternatives (ms-,me-,ps-,pe-,start,end). - Targeted Test Execution: Always run tests targeting specific component files to conserve tokens and reduce execution time (do not run full project test suites during component iterations).
- Storybook Story Separation: Do not author
.stories.tsxor run Storybook builds during standard component development unless thenextjs-storybook-storyskill is specifically requested. Consultreferences/storybook-reference.md.