Communitygithub.com

ComeOnOliver/skillshub

Use ao trabalhar com tarefas do Next.js App Router - criação de páginas em /app/, configuração de rotas dinâmicas ([id]/page.tsx), implementação de layouts/modelos aninhados (layout.tsx), otimização de componentes Server/Client, ou construção de páginas baseadas em funções ERP (painéis admin/professor/estudante). Uso automático para todas as operações no diretório /app/, roteamento dinâmico e recursos específicos do App Router.

O que é skillshub?

Este skill especializa-se em orientar o desenvolvimento com o Next.js App Router, cobrindo desde a criação de páginas simples até a implementação de arquiteturas complexas para sistemas ERP. Ele fornece templates e regras claras para páginas estáticas, rotas dinâmicas com parâmetros, layouts aninhados e paralelos, e a distinção crucial entre Server Components (mais performáticos, sem JavaScript no cliente) e Client Components (interativos, com hooks e eventos). A habilidade também inclui padrões para autenticação baseada em papéis, integração com shadcn/ui, tratamento de erros com error.tsx, estados de carregamento com Suspense e loading.tsx, e criação de dashboards com gráficos usando Recharts. O skill é ideal para desenvolvedores que trabalham com Next.js 14+ e desejam construir aplicações ERP robustas, role-based e otimizadas para SEO, seguindo as melhores práticas do framework.

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

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Especialista em Next.js App Router

Visão Geral

Orientação especializada para desenvolvimento com Next.js App Router, incluindo criação de páginas, roteamento dinâmico, layouts aninhados, otimização de componentes Server/Client e painéis baseados em papéis ERP.

Capacidades Principais

1. Criação de Páginas (/app/.../page.tsx)

Regras:

  • Use Server Components por padrão (sem diretiva 'use client')
  • Busca de dados assíncrona com fetch() ou consultas ORM diretamente
  • Sem useEffect para carregamento inicial de dados
  • Use limites Suspense para estados de carregamento
  • Metadados SEO via generateMetadata()

Modelo:

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

export const metadata = {
  title: 'Dashboard',
  description: 'Seu painel de gerenciamento de tarefas',
};

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

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

2. Rotas Dinâmicas ([slug]/page.tsx)

Quando usar:

  • Perfis de estudante: app/students/[studentId]/page.tsx
  • Detalhes de tarefa: app/tasks/[taskId]/page.tsx
  • Páginas de curso: app/courses/[courseId]/page.tsx

Regras:

  • Extraia parâmetros da prop params (somente leitura)
  • Use generateMetadata() para SEO
  • Trate 404 com not-found.tsx

Modelo:

// 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: 'Estudante Não Encontrado' };

  return {
    title: `${student.name} - Perfil do Estudante`,
  };
}

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. Rotas Paralelas (@folder)

Quando usar:

  • Variantes de dashboard: app/dashboard@(admin|teacher)/page.tsx
  • Layouts divididos: app/settings@(user|organization)/layout.tsx

Modelo:

// app/dashboard/@admin/page.tsx - Dashboard do admin
 export default function AdminDashboard() {
   return <AdminPanel />;
 }

 // app/dashboard/@teacher/page.tsx - Dashboard do professor
 export default function TeacherDashboard() {
   return <TeacherPanel />;
 }

4. Layouts e Modelos

Layout Raiz (app/layout.tsx):

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

export const metadata = {
  title: 'Todo Evolution',
  description: 'Gerenciamento de tarefas para educação',
};

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

Layout Aninhado (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>
  );
}

Modelo (app/tasks/template.tsx):

// Reexecuta na navegação, preserva o estado do formulário
 export default function TasksTemplate({ children }: { children: React.ReactNode }) {
   return (
     <div className="bg-gray-50 min-h-screen">
       <header className="bg-white shadow">
         <h1>Tarefas</h1>
       </header>
       {children}
     </div>
   );
 }

5. Componentes Server vs Client

Use Server Components para:

  • Busca de dados
  • Consultas diretas ao banco de dados
  • Conteúdo estático
  • Operações exclusivas do servidor

Use Client Components ('use client') para:

  • APIs do navegador (window, localStorage)
  • Manipuladores de eventos (onClick, onSubmit)
  • Hooks React (useState, useEffect)
  • Gerenciamento de estado (Zustand, Redux)
  • Interatividade
// Server Component (padrão)
 export default async function TaskList() {
   const tasks = await fetchTasks(); // Consulta direta ao BD
   return <div>{tasks.map(/* ... */)}</div>;
 }

 // Client Component
 'use client';
 import { useTaskStore } from '@/store/tasks';

 export function TaskFilter() {
   const { filter, setFilter } = useTaskStore();
   return <button onClick={() => setFilter('all')}>Todas as Tarefas</button>;
 }

6. Páginas Baseadas em Papéis ERP

Guardas de Papel:

// 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 />;
}

Dashboard 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. Estados de Erro e Carregamento

Limite de Erro (error.tsx):

'use client';
export default function Error({
  error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  return (
    <div>
      <h2>Algo deu errado!</h2>
      <button onClick={reset}>Tentar novamente</button>
    </div>
  );
}

Estado de Carregamento (loading.tsx):

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

// Ou com Suspense:
export default async function Page() {
  return (
    <Suspense fallback={<Loading />}>
      <Content />
    </Suspense>
  );
}

8. Integração shadcn/ui

Instalação:

npx shadcn@latest add button card input dialog

Uso em Server Components:

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>Tarefas</CardHeader>
      <CardContent>
        {tasks.map(task => (
          <div key={task.id}>{task.title}</div>
        ))}
      </CardContent>
    </Card>
  );
}

Árvore de Decisão do Fluxo de Trabalho

Solicitação do Usuário → Analisar → Caminho de Implementação

  1. "Criar página Dashboard/Admin" → Server Component com page.tsx → Busca de dados assíncrona → Adicionar layout.tsx se necessário para navegação

  2. "Perfil dinâmico de estudante" → Criar [studentId]/page.tsx → Extrair parâmetros → Adicionar generateMetadata() → Criar not-found.tsx se necessário

  3. "Adicionar layout compartilhado" → Criar layout.tsx na pasta alvo → Envolver com providers se necessário → Manter a renderização de children

  4. "Adicionar formulário" → Componente 'use client' → useState para dados do formulário → Server Action para envio OU rota de API

  5. "Gráficos KPI / Analytics" → 'use client' para Recharts → Parent Server Component com busca de dados → Passar dados como props

Lista de Verificação de Qualidade

Antes de marcar a tarefa como concluída:

  • Modo estrito TypeScript ativado
  • Server Components usados por padrão
  • 'use client' somente quando necessário
  • generateMetadata() para SEO
  • Limites Suspense para dados assíncronos
  • Limites de erro (error.tsx) onde necessário
  • Sem incompatibilidades de hidratação
  • Performance otimizada (sem renderizações bloqueantes)
  • Design responsivo mobile-first
  • Acessível (rótulos ARIA, navegação por teclado)

Padrões Comuns

Padrão 1: Mistura de Server Component + Client Component

// Server Component
 export default async function Page() {
   const tasks = await fetchTasks();
   return <TaskList tasks={tasks} />; // Client component para interatividade
 }

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

Padrão 2: Grupos de Rotas para Organização

app/
  (marketing)/     # Grupo: sem segmento de URL
    about/page.tsx
    contact/page.tsx
  (dashboard)/      # Grupo: sem segmento de URL
    layout.tsx
    page.tsx

Padrão 3: Rotas de API (Route Handlers)

// 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 });
}

Exemplos de Disparo

  • "Criar página Dashboard" → Gerar app/dashboard/page.tsx com server component
  • "Rota dinâmica de perfil de estudante" → app/students/[studentId]/page.tsx com parâmetros e metadados
  • "Adicionar layout compartilhado" → app/dashboard/layout.tsx com children
  • "Painel admin com gráficos" → Server component + Client component de gráfico
  • "Criar página de login" → Componente formulário 'use client' + rota de API
  • "Personalizar página 404" → app/not-found.tsx
  • "Tratar erro" → app/dashboard/error.tsx

Referências

Consulte references/app-router-patterns.md para padrões avançados e references/api-routes.md para exemplos de route handlers.

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

Habilidades Relacionadas