nextjs-app-router-patterns
Skill8 starsChanged 9 months agoMITView on GitHub
Next.js App Router patterns — server vs client components, data fetching, caching, streaming, parallel routes, and error boundaries
22 other projects use a version of this.
Adopted by
Most recently taken up by
- Rain-kl/OpenFlaretheir own version, first seen Nov 30, 2026
- gromov0737/skillstheir own version, first seen Nov 29, 2026
- aakash1552005/universal-agent-skillstheir own version, first seen Nov 29, 2026
- hybridlabor-api/aostheir own version, first seen Nov 29, 2026
- Lukk17/agent-standardstheir own version, first seen Nov 24, 2026
- AtilaMedeiros/skillstheir own version, first seen Nov 16, 2026
Used with
Projects with it also use tdd.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
GoogleSkilltdd
Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests.
Also in 3 projects that use this
Other versions22 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 22
- Rain-kl/OpenFlare★ 305same name
- Fandry96/k3-agentic-skills★ 27same name
- hybridlabor-api/aos★ 9same name
- xfstudio/skills★ 9same name
- aakash1552005/universal-agent-skills★ 4same name
- GPTtang/skill-atlas★ 4same name
- FimawLLC/fimaw-skills★ 3same name
- ai4brands-design/claude-skills★ 2same name
- CodeWithBehnam/cc-docs★ 2same name
- gromov0737/skills★ 2same name
12 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository79 other files it gives its agents.
- AGENTS.mdAGENTS.md
- analyze-competitorsSkill
- analyze-dependenciesSkill
- analyze-metricsSkill
- audit-accessibilitySkill
- audit-api-consistencySkill
- audit-performanceSkill
- audit-securitySkill
- capture-pr-visualsSkill
- commitSkill
- create-adrSkill
- create-api-designSkill
- create-bug-reportSkill
- create-commit-messageSkill
- create-data-modelSkill
- create-decision-logSkill
- create-docSkill
- create-estimationSkill
- create-experiment-designSkill
- create-feature-flag-planSkill
- create-gtm-briefSkill
- create-handoffSkill
- create-incident-reportSkill
- create-interview-guideSkill
- create-jtbd-canvasSkill
- create-metrics-frameworkSkill
- create-onboarding-guideSkill
- create-ostSkill
- create-planSkill
- create-postmortemSkill
- create-pr-descriptionSkill
- create-prdSkill
- create-prSkill
- create-release-checklistSkill
- create-release-notesSkill
- create-retroSkill
- create-reviewSkill
- create-rfcSkill
- create-roadmapSkill
- create-rollback-planSkill
- create-runbookSkill
- create-shape-up-pitchSkill
- create-stakeholder-updateSkill
- create-test-planSkill
- create-threat-modelSkill
- create-user-storiesSkill
- debug-systematicSkill
- fastapi-endpoint-patternsSkill
- fix-findingsSkill
- fix-reviewSkill
- flutter-platform-patternsSkill
- flutter-state-managementSkill
- flutter-version-managementSkill
- flutter-widget-patternsSkill
- manage-tech-debtSkill
- nextjs-api-patternsSkill
- nextjs-performanceSkill
- product-context-docsSkill
- project-skill-creatorSkill
- project-standardsSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
1 rule. 0 are common, 1 is distinctive, and 0 are very specific to this project.
0
Common
Most of the 22 edited versions we read keep these.
1
Distinctive
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 43
Keep the boundary as low as possible.
“Common” is measured: kept by at least 6 in 10 of the 22 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Next.js App Router Patterns
Overview
Reference guide for idiomatic Next.js 14+ App Router patterns. Apply these when building pages, layouts, and data flows to fully leverage server components, streaming, and the caching system.
Server vs Client Component Decision Tree
Does the component need...
├── Browser APIs (window, localStorage, navigator)?
│ └── YES → "use client"
├── Event listeners (onClick, onChange, onSubmit)?
│ └── YES → "use client"
├── useState, useEffect, useRef, or custom hooks?
│ └── YES → "use client"
├── Only data fetching and rendering?
│ └── YES → Server Component (default) ✓
├── Third-party library that uses hooks or browser APIs?
│ └── YES → "use client" wrapper component
└── Static content (no interactivity)?
└── YES → Server Component (default) ✓Key Principle: Push "use client" Down
Keep the boundary as low as possible. Only the interactive leaf should be a client component.
app/
dashboard/
page.tsx ← Server Component (fetches data)
DashboardGrid.tsx ← Server Component (layout)
MetricCard.tsx ← Server Component (displays data)
ChartWidget.tsx ← "use client" (uses chart library with hooks)
FilterBar.tsx ← "use client" (has onChange handlers)// app/dashboard/page.tsx — Server Component
import { getMetrics } from "@/lib/data";
import { DashboardGrid } from "./DashboardGrid";
import { FilterBar } from "./FilterBar";
export default async function DashboardPage() {
const metrics = await getMetrics(); // Direct DB/API call, no useEffect
return (
<div>
<FilterBar /> {/* Client island for interactivity */}
<DashboardGrid metrics={metrics} /> {/* Server component */}
</div>
);
}Data Fetching Patterns
Server Components: Direct Async
// app/users/page.tsx
import { db } from "@/lib/db";
export default async function UsersPage() {
const users = await db.user.findMany({
orderBy: { createdAt: "desc" },
});
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}Parallel Data Fetching
Fetch multiple resources in parallel with Promise.all to avoid waterfalls.
export default async function ProfilePage({ params }: { params: { id: string } }) {
// Parallel — both start immediately
const [user, posts] = await Promise.all([
getUser(params.id),
getUserPosts(params.id),
]);
return (
<>
<UserHeader user={user} />
<PostList posts={posts} />
</>
);
}Data Fetching with Preloading
For components deeper in the tree, use the preload pattern.
// lib/data.ts
import { cache } from "react";
export const getUser = cache(async (id: string) => {
return db.user.findUnique({ where: { id } });
});
// Preload function — call early, consume later
export const preloadUser = (id: string) => {
void getUser(id);
};
// app/user/[id]/page.tsx
import { getUser, preloadUser } from "@/lib/data";
export default async function UserPage({ params }: { params: { id: string } }) {
preloadUser(params.id); // Start fetch early
// ... other work ...
const user = await getUser(params.id); // Deduplicated, may already be resolved
return <Profile user={user} />;
}Caching Strategies
Fetch Cache (Request Deduplication)
// These two calls in the same render are automatically deduplicated
async function UserName({ id }: { id: string }) {
const user = await fetch(`/api/users/${id}`); // cached
return <span>{user.name}</span>;
}
async function UserAvatar({ id }: { id: string }) {
const user = await fetch(`/api/users/${id}`); // same URL = deduplicated
return <img src={user.avatar} />;
}Revalidation
// Time-based revalidation
const data = await fetch(url, { next: { revalidate: 60 } }); // Revalidate every 60s
// On-demand revalidation (in a Server Action or Route Handler)
import { revalidatePath, revalidateTag } from "next/cache";
// By path
revalidatePath("/dashboard");
// By tag
const data = await fetch(url, { next: { tags: ["users"] } });
// Later:
revalidateTag("users");
// Opt out of caching
const data = await fetch(url, { cache: "no-store" });Route Segment Config
// app/dashboard/layout.tsx
export const dynamic = "force-dynamic"; // Never cache this segment
export const revalidate = 60; // Revalidate every 60sStreaming with Suspense
Wrap slow parts in Suspense to stream the page progressively.
// app/dashboard/page.tsx
import { Suspense } from "react";
import { SlowAnalytics } from "./SlowAnalytics";
import { QuickSummary } from "./QuickSummary";
export default function DashboardPage() {
return (
<div>
{/* Renders immediately */}
<QuickSummary />
{/* Streams in when ready */}
<Suspense fallback={<AnalyticsSkeleton />}>
<SlowAnalytics />
</Suspense>
</div>
);
}Loading States (file convention)
app/
dashboard/
page.tsx
loading.tsx ← Automatic Suspense boundary for the page
error.tsx ← Error boundary for the segment
not-found.tsx ← Shown when notFound() is called// app/dashboard/loading.tsx
export default function Loading() {
return <DashboardSkeleton />;
}Parallel Routes
Render multiple pages in the same layout simultaneously.
app/
@analytics/
page.tsx ← Analytics panel
loading.tsx
@feed/
page.tsx ← Feed panel
loading.tsx
layout.tsx ← Receives both as props// app/layout.tsx
export default function Layout({
children,
analytics,
feed,
}: {
children: React.ReactNode;
analytics: React.ReactNode;
feed: React.ReactNode;
}) {
return (
<div className="grid grid-cols-3">
<main className="col-span-2">{children}</main>
<aside>
{analytics}
{feed}
</aside>
</div>
);
}Intercepting Routes
Show a route in a modal while preserving the background page.
app/
photos/
[id]/
page.tsx ← Full photo page (direct navigation)
@modal/
(.)photos/[id]/
page.tsx ← Modal overlay (intercepted from feed)
default.tsx ← Returns null when no modal active
layout.tsx
page.tsx ← Photo feed// app/@modal/(.)photos/[id]/page.tsx
import { Modal } from "@/components/Modal";
import { getPhoto } from "@/lib/data";
export default async function PhotoModal({ params }: { params: { id: string } }) {
const photo = await getPhoto(params.id);
return (
<Modal>
<img src={photo.url} alt={photo.alt} />
</Modal>
);
}Error Boundaries
// app/dashboard/error.tsx
"use client"; // Error boundaries must be client components
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
return (
<div role="alert">
<h2>Something went wrong</h2>
<p>{error.message}</p>
<button onClick={reset}>Try again</button>
</div>
);
}Anti-patterns
"use client" on Everything
Adding "use client" to every component defeats the purpose of RSC. You lose direct data access, increase bundle size, and add unnecessary hydration.
Client-side Data Fetching When Server Would Work
// BAD: useEffect + fetch in a page component
"use client";
export default function UsersPage() {
const [users, setUsers] = useState([]);
useEffect(() => { fetch("/api/users").then(/* ... */) }, []);
}
// GOOD: Server component with direct data access
export default async function UsersPage() {
const users = await db.user.findMany();
return <UserList users={users} />;
}Misunderstanding Caching
fetchin server components is cached by default in productionPOSTrequests are NOT cached- Route Handlers with
GETare cached when usingexport const dynamic = "auto" - Dynamic functions (
cookies(),headers(),searchParams) opt the entire route out of static rendering
Not Leveraging Layouts
Layouts persist across navigations and do not re-render. Put shared UI (nav, sidebar) in layouts, not in every page.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

