Communitygithub.com

Next.js App Router Expert

Next.js App Router 개발에 대한 전문 가이드: 페이지 생성, 동적 라우팅, 중첩 레이아웃, 서버/클라이언트 컴포넌트 최적화 및 ERP 역할 기반 대시보드 구축을 지원합니다.

Next.js App Router Expert란 무엇인가요?

이 스킬은 Next.js App Router를 사용한 현대적인 웹 애플리케이션 개발을 위한 포괄적인 가이드를 제공합니다. 개발자는 `/app/` 디렉토리 내 페이지 생성, 동적 라우트(`[id]/page.tsx`) 설정, 중첩 레이아웃 및 템플릿(`layout.tsx`, `template.tsx`) 구현, 서버/클라이언트 컴포넌트 최적화와 같은 핵심 기능을 쉽게 구현할 수 있습니다. 특히 ERP 시스템에서 필요한 관리자, 교사, 학생 역할 기반 대시보드 구축을 위한 권한 가드 및 KPI 차트(Recharts) 통합 패턴도 제공합니다. 또한 shadcn/ui 컴포넌트 통합, 오류 바운더리, 로딩 상태 처리, 라우트 그룹화, API 라우트 핸들러 등 생산성 있는 Next.js 개발에 필요한 모든 패턴을 포함하고 있습니다. 각 기능에 대한 결정 트리와 품질 체크리스트를 제공하여 AI 에이전트가 일관된 고품질 코드를 생성하도록 돕습니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/awais68/frontend-nextjs-app-router

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

Next.js App Router Expert은(는) 무엇을 하나요?

개요

Next.js App Router 개발을 위한 전문 가이드: 페이지 생성, 동적 라우팅, 중첩 레이아웃, 서버/클라이언트 컴포넌트 최적화 및 ERP 역할 기반 대시보드 구축을 다룹니다.

핵심 기능

1. 페이지 생성 (/app/.../page.tsx)

규칙:

  • 기본적으로 서버 컴포넌트 사용 ('use client' 지시어 없음)
  • fetch() 또는 ORM 쿼리를 사용한 비동기 데이터 페칭
  • 초기 데이터 로드에 useEffect 사용 금지
  • 로딩 상태에 Suspense 경계 사용
  • generateMetadata()를 통한 SEO 메타데이터

템플릿:

// app/dashboard/page.tsx
import { Suspense } from 'react';
import { TaskList } from '@/components/TaskList';
import { TaskListSkeleton } from '@/components/TaskListSkeleton';

export const metadata = {
  title: '대시보드',
  description: '할 일 관리 대시보드',
};

export default async function DashboardPage() {
  const tasks = await fetchTasks();

  return (
    <main className="p-4">
      <h1>대시보드</h1>
      <Suspense fallback={<TaskListSkeleton />}>
        <TaskList initialTasks={tasks} />
      </Suspense>
    </main>
  );
}

2. 동적 라우트 ([slug]/page.tsx)

사용 시점:

  • 학생 프로필: app/students/[studentId]/page.tsx
  • 할 일 상세: app/tasks/[taskId]/page.tsx
  • 강좌 페이지: app/courses/[courseId]/page.tsx

규칙:

  • params prop에서 파라미터 추출 (읽기 전용)
  • SEO를 위해 generateMetadata() 사용
  • not-found.tsx로 404 처리

템플릿:

// app/students/[studentId]/page.tsx
import { notFound } from 'next/navigation';

type Params = Promise<{ studentId: string }>;

export async function generateMetadata({ params }: { params: Params }) {
  const { studentId } = await params;
  const student = await getStudent(studentId);

  if (!student) return { title: '학생을 찾을 수 없음' };

  return {
    title: `${student.name} - 학생 프로필`,
  };
}

export default async function StudentProfile({ params }: { params: Params }) {
  const { studentId } = await params;
  const student = await getStudent(studentId);

  if (!student) notFound();

  return <StudentProfileView student={student} />;
}

3. 병렬 라우트 (@folder)

사용 시점:

  • 대시보드 변형: app/dashboard@(admin|teacher)/page.tsx
  • 분할 레이아웃: app/settings@(user|organization)/layout.tsx

템플릿:

// app/dashboard/@admin/page.tsx - 관리자 대시보드
export default function AdminDashboard() {
  return <AdminPanel />;
}

// app/dashboard/@teacher/page.tsx - 교사 대시보드
export default function TeacherDashboard() {
  return <TeacherPanel />;
}

4. 레이아웃과 템플릿

루트 레이아웃 (app/layout.tsx):

import { Providers } from '@/components/Providers';
import './globals.css';

export const metadata = {
  title: 'Todo Evolution',
  description: '교육을 위한 할 일 관리',
};

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="ko">
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  );
}

중첩 레이아웃 (app/dashboard/layout.tsx):

import { DashboardNav } from '@/components/DashboardNav';

export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <div className="flex min-h-screen">
      <DashboardNav />
      <main className="flex-1 p-6">{children}</main>
    </div>
  );
}

템플릿 (app/tasks/template.tsx):

// 탐색 시 다시 실행, 폼 상태 유지
export default function TasksTemplate({ children }: { children: React.ReactNode }) {
  return (
    <div className="bg-gray-50 min-h-screen">
      <header className="bg-white shadow">
        <h1>할 일 목록</h1>
      </header>
      {children}
    </div>
  );
}

5. 서버 vs 클라이언트 컴포넌트

서버 컴포넌트 사용:

  • 데이터 페칭
  • 직접 데이터베이스 쿼리
  • 정적 콘텐츠
  • 서버 전용 작업

클라이언트 컴포넌트 ('use client') 사용:

  • 브라우저 API (window, localStorage)
  • 이벤트 핸들러 (onClick, onSubmit)
  • React 훅 (useState, useEffect)
  • 상태 관리 (Zustand, Redux)
  • 상호작용
// 서버 컴포넌트 (기본값)
export default async function TaskList() {
  const tasks = await fetchTasks(); // 직접 DB 쿼리
  return <div>{tasks.map(/* ... */)}</div>;
}

// 클라이언트 컴포넌트
'use client';
import { useTaskStore } from '@/store/tasks';

export function TaskFilter() {
  const { filter, setFilter } = useTaskStore();
  return <button onClick={() => setFilter('all')}>모든 할 일</button>;
}

6. ERP 역할 기반 페이지

역할 가드:

// app/admin/page.tsx
import { requireRole } from '@/lib/auth';
import { redirect } from 'next/navigation';

export default async function AdminPage() {
  const session = await getSession();

  if (session?.role !== 'admin') {
    redirect('/unauthorized');
  }

  return <AdminDashboard />;
}

KPI 대시보드 (Recharts):

'use client';
import { BarChart, Bar, XAxis, YAxis, Tooltip } from 'recharts';

export function TaskKPIChart({ data }: { data: TaskStats[] }) {
  return (
    <BarChart width={600} height={300} data={data}>
      <XAxis dataKey="date" />
      <YAxis />
      <Tooltip />
      <Bar dataKey="completed" fill="#22c55e" />
    </BarChart>
  );
}

7. 오류 및 로딩 상태

오류 바운더리 (error.tsx):

'use client';
export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  return (
    <div>
      <h2>문제가 발생했습니다!</h2>
      <button onClick={reset}>다시 시도</button>
    </div>
  );
}

로딩 상태 (loading.tsx):

export default function Loading() {
  return <div className="animate-pulse">로딩 중...</div>;
}

// 또는 Suspense 사용:
export default async function Page() {
  return (
    <Suspense fallback={<Loading />}>
      <Content />
    </Suspense>
  );
}

8. shadcn/ui 통합

설치:

npx shadcn@latest add button card input dialog

서버 컴포넌트에서 사용:

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader } from '@/components/ui/card';

export default async function TaskPage() {
  const tasks = await getTasks();

  return (
    <Card>
      <CardHeader>할 일</CardHeader>
      <CardContent>
        {tasks.map(task => (
          <div key={task.id}>{task.title}</div>
        ))}
      </CardContent>
    </Card>
  );
}

워크플로우 결정 트리

사용자 요청 → 분석 → 구현 경로

  1. "대시보드/관리자 페이지 만들어 줘" → page.tsx를 사용한 서버 컴포넌트 → 비동기 데이터 페칭 → 탐색이 필요하면 layout.tsx 추가

  2. "동적 학생 프로필" → [studentId]/page.tsx 생성 → 파라미터 추출 → generateMetadata() 추가 → 필요한 경우 not-found.tsx 생성

  3. "공유 레이아웃 추가해 줘" → 대상 폴더에 layout.tsx 생성 → 필요한 경우 프로바이더로 감싸기 → children 렌더링 유지

  4. "폼 추가해 줘" → 'use client' 컴포넌트 → 폼 데이터에 useState 사용 → 제출을 위한 서버 액션 또는 API 라우트

  5. "KPI 차트/분석" → Recharts를 위한 'use client' → 데이터 페치를 포함한 서버 컴포넌트 부모 → 데이터를 props로 전달

품질 체크리스트

작업 완료 표시 전 확인:

  • TypeScript strict mode 활성화
  • 기본적으로 서버 컴포넌트 사용
  • 필요한 경우에만 'use client'
  • SEO를 위한 generateMetadata()
  • 비동기 데이터를 위한 Suspense 경계
  • 필요한 곳에 오류 바운더리 (error.tsx)
  • 수화 불일치 없음
  • 성능 최적화 (렌더링 차단 없음)
  • 모바일 우선 반응형 디자인
  • 접근성 (ARIA 레이블, 키보드 탐색)

공통 패턴

패턴 1: 서버 컴포넌트 + 클라이언트 컴포넌트 혼합

// 서버 컴포넌트
export default async function Page() {
  const tasks = await fetchTasks();
  return <TaskList tasks={tasks} />; // 상호작용을 위한 클라이언트 컴포넌트
}

'use client';
function TaskList({ tasks }: { tasks: Task[] }) {
  const [filter, setFilter] = useState('all');
  const filtered = tasks.filter(/* ... */);
  return <div>{filtered.map(/* ... */)}</div>;
}

패턴 2: 조직을 위한 라우트 그룹

app/
  (marketing)/     # 그룹: URL 세그먼트 없음
    about/page.tsx
    contact/page.tsx
  (dashboard)/      # 그룹: URL 세그먼트 없음
    layout.tsx
    page.tsx

패턴 3: API 라우트 (라우트 핸들러)

// app/api/tasks/route.ts
import { NextResponse } from 'next/server';

export async function GET() {
  const tasks = await db.query.tasks.findMany();
  return NextResponse.json(tasks);
}

export async function POST(request: Request) {
  const body = await request.json();
  const task = await createTask(body);
  return NextResponse.json(task, { status: 201 });
}

트리거 예시

  • "대시보드 페이지 만들어 줘" → 서버 컴포넌트로 app/dashboard/page.tsx 생성
  • "동적 학생 프로필 라우트" → app/students/[studentId]/page.tsx (params, metadata 포함)
  • "공유 레이아웃 추가해 줘" → app/dashboard/layout.tsx (children 포함)
  • "관리자 패널 차트 포함" → 서버 컴포넌트 + 클라이언트 차트 컴포넌트
  • "로그인 페이지 만들어 줘" → 'use client' 폼 컴포넌트 + API 라우트
  • "404 페이지 커스터마이즈" → app/not-found.tsx
  • "오류 처리해 줘" → app/dashboard/error.tsx

참고 자료

고급 패턴은 references/app-router-patterns.md를, 라우트 핸들러 예제는 references/api-routes.md를 참조하세요.

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

관련 스킬