Skip to content

artubss/SKILLS-CLAUDE-CODE / favorites/tpl-frontend-nextjs-app-router

tpl-frontend-nextjs-app-router

Verified

Template do pack (frontend/03-nextjs-app-router.md). Orienta o agente em interfaces, componentes e apps de frontend alinhado a esse contexto.

PROJECT: [Nome do App]

Skill gerado a partir do pack templates-claude-code. Arquivo de origem: frontend/03-nextjs-app-router.md. Use como baseline e adapte ao projeto antes de mudancas grandes.

Conteudo do template

CLAUDE.md — Next.js 15 App Router + TypeScript + Drizzle ORM Gerado pelo Pack CLAUDE.md Elite


STACK

CamadaTecnologiaVersão
FrameworkNext.js (App Router)15.x
LinguagemTypeScript5.x (strict)
DatabaseNeon Postgres + Drizzle ORMlatest
AuthNextAuth.js (Auth.js)v5
StylingTailwind CSS + shadcn/uiv4
Server StateServer Components + TanStack Queryv5
FormsServer Actions + Zodlatest
TestsVitest (unit) + Playwright (e2e)latest

APP ROUTER MENTAL MODEL

app/
├── (public)/            # Route group — sem auth
│   ├── layout.tsx
│   └── page.tsx
├── (dashboard)/         # Route group — requer auth
│   ├── layout.tsx       # Verifica sessão no Server Component
│   ├── loading.tsx      # Suspense fallback automático
│   ├── error.tsx        # Error boundary automático
│   └── {feature}/
│       ├── page.tsx     # Server Component (busca dados direto)
│       ├── actions.ts   # Server Actions (mutações)
│       └── _components/ # Prefixo _ = privado (não vira rota)
├── api/
│   └── {resource}/
│       └── route.ts     # Route Handler (webhooks, integrations)
└── globals.css

Regra do _ prefix: Qualquer pasta/arquivo com _ é PRIVADO — Next.js não cria rota. Use para colocar componentes específicos de uma rota.


COMPONENT STRATEGY — Server vs Client

┌─────────────────────────────────────────────────┐
│ Server Component (DEFAULT — sem "use client")   │
│   ✅ async/await direto                          │
│   ✅ Acesso a DB, env vars, fs                   │
│   ✅ ZERO JavaScript no bundle do client         │
│   ❌ Sem hooks, sem eventos, sem browser APIs    │
├─────────────────────────────────────────────────┤
│ Client Component ("use client" no topo)         │
│   ✅ useState, useEffect, onClick, onSubmit     │
│   ✅ TanStack Query, Zustand, browser APIs      │
│   ❌ Sem acesso direto a DB ou server secrets   │
└─────────────────────────────────────────────────┘

REGRA: Empurre "use client" para as FOLHAS da árvore.
Server Component → renderiza → passa dados via props → Client Component filho

Exemplo: Server Component buscando dados

// app/(dashboard)/users/page.tsx — SERVER COMPONENT (default)
import { db } from '@/lib/db';
import { users } from '@/db/schema';
import { UserTable } from './_components/UserTable';

export default async function UsersPage() {
  const allUsers = await db.select().from(users).orderBy(users.createdAt);
  return (
    <div>
      <h1>Usuários</h1>
      <UserTable users={allUsers} />
    </div>
  );
}

Exemplo: Client Component com interação

// app/(dashboard)/users/_components/UserTable.tsx
'use client';
import { useState } from 'react';
import type { User } from '@/db/schema';

export function UserTable({ users }: { users: User[] }) {
  const [search, setSearch] = useState('');
  const filtered = users.filter((u) => u.name?.includes(search));
  return (
    <>
      <input value={search} onChange={(e) => setSearch(e.target.value)} />
      <table>{/* ... render filtered */}</table>
    </>
  );
}

DATA FETCHING RULES

OndeComoQuando
Server Componentasync/await direto com DrizzleDados iniciais da página
Client ComponentTanStack Query (useQuery)Dados que mudam em tempo real
Server Action"use server" + Zod + DBFormulários, mutações
Route Handlerapp/api/*/route.tsWebhooks externos, CORS APIs

SERVER ACTIONS PATTERN (Mutações)

// app/(dashboard)/users/actions.ts
'use server';
import { z } from 'zod';
import { db } from '@/lib/db';
import { users } from '@/db/schema';
import { revalidatePath } from 'next/cache';
import { auth } from '@/lib/auth';

const createUserSchema = z.object({
  name: z.string().min(2, 'Nome precisa ter pelo menos 2 caracteres'),
  email: z.string().email('Email inválido'),
  role: z.enum(['admin', 'member']),
});

export async function createUser(formData: FormData) {
  // 1. Auth check
  const session = await auth();
  if (!session?.user) throw new Error('Unauthorized');

  // 2. Validate input
  const parsed = createUserSchema.safeParse(Object.fromEntries(formData));
  if (!parsed.success) return { error: parsed.error.flatten() };

  // 3. DB operation
  const [user] = await db.insert(users).values(parsed.data).returning();

  // 4. Revalidate cache
  revalidatePath('/dashboard/users');
  return { data: user };
}

export async function deleteUser(id: string) {
  const session = await auth();
  if (session?.user?.role !== 'admin') throw new Error('Forbidden');

  await db.delete(users).where(eq(users.id, id));
  revalidatePath('/dashboard/users');
}

MIDDLEWARE PATTERN (Auth + Redirects)

// middleware.ts (raiz do projeto)
import { auth } from '@/lib/auth';
import { NextResponse } from 'next/server';

export default auth((req) => {
  const { pathname } = req.nextUrl;

  // Rotas protegidas
  if (pathname.startsWith('/dashboard') && !req.auth) {
    return NextResponse.redirect(new URL('/login', req.url));
  }

  // Redirect logged user away from login
  if (pathname === '/login' && req.auth) {
    return NextResponse.redirect(new URL('/dashboard', req.url));
  }
});

export const config = {
  matcher: ['/dashboard/:path*', '/login'],
};

ROUTING TABLE (trigger → action)

TriggerAction
New featurePlan Server/Client split → route group folder → page.tsx + actions.ts
Hydration errorFind "use client" boundary — move event handlers to leaf component
Auth on pagemiddleware.ts matcher + session check in Server Component layout
SEO neededExport metadata or generateMetadata from page.tsx
Mutation with feedbackServer Action → useActionState (React 19) or TanStack useMutation
Real-time neededRoute Handler + SSE or external WebSocket
Loading state neededAdd loading.tsx to route segment (auto-Suspense)
Error handlingAdd error.tsx to route segment (auto-ErrorBoundary)

DRIZZLE SCHEMA RULES

// db/schema/users.ts
import { pgTable, text, timestamp, boolean } from 'drizzle-orm/pg-core';

export const users = pgTable('users', {
  id: text('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
  email: text('email').unique().notNull(),
  name: text('name').notNull(),
  role: text('role', { enum: ['admin', 'member'] }).default('member').notNull(),
  createdAt: timestamp('created_at').defaultNow().notNull(),
  updatedAt: timestamp('updated_at').defaultNow().notNull(),
});

export type User = typeof users.$inferSelect;
export type NewUser = typeof users.$inferInsert;

Rules:

  • One file per table: db/schema/{table}.ts
  • Always createdAt + updatedAt
  • Foreign keys declared explicitly
  • Index on all columns used in WHERE
  • Type exports: $inferSelect and $inferInsert

METADATA & SEO

// app/(public)/blog/[slug]/page.tsx
import type { Metadata } from 'next';

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const post = await getPost(params.slug);
  return {
    title: post.title,
    description: post.excerpt,
    openGraph: {
      title: post.title,
      images: [{ url: post.ogImage }],
    },
  };
}

TESTING PATTERNS

// __tests__/users/actions.test.ts
import { describe, it, expect, vi } from 'vitest';
import { createUser } from '@/app/(dashboard)/users/actions';

vi.mock('@/lib/auth', () => ({
  auth: vi.fn(() => ({ user: { id: '1', role: 'admin' } })),
}));

vi.mock('@/lib/db', () => ({
  db: { insert: vi.fn().mockReturnThis(), values: vi.fn().mockReturnThis(),
    returning: vi.fn(() => [{ id: '2', name: 'Test', email: 'test@test.com' }]),
  },
}));

describe('createUser', () => {
  it('validates input with Zod', async () => {
    const formData = new FormData();
    formData.set('name', '');
    formData.set('email', 'invalid');
    formData.set('role', 'member');

    const result = await createUser(formData);
    expect(result.error).toBeDefined();
  });
});

NAMING CONVENTIONS

TipoPadrãoExemplo
Pagespage.tsx (App Router)app/(dashboard)/users/page.tsx
Layoutslayout.tsxapp/(dashboard)/layout.tsx
Actionsactions.tsapp/(dashboard)/users/actions.ts
Route Handlersroute.tsapp/api/webhooks/route.ts
ComponentsPascalCaseUserCard.tsx in _components/
Private folders_prefix_components/, _hooks/
DB Schemasnake_casedb/schema/user_profiles.ts
TypesPascalCaseUser, ApiResponse<T>

ENV VARS

DATABASE_URL=postgresql://...neon.tech/...
NEXTAUTH_SECRET=...
NEXTAUTH_URL=http://localhost:3000
NEXT_PUBLIC_APP_URL=http://localhost:3000

BUILD COMMANDS

npm run dev          # Dev server (turbopack)
npm run build        # Production build (tsc + next build)
npm run start        # Start production server
npm test             # Vitest
npm run test:e2e     # Playwright
npm run db:generate  # Drizzle Kit generate migration
npm run db:migrate   # Apply migrations
npm run db:studio    # Drizzle Studio (visual DB browser)

QUALITY GATES

Before any PR: □ next build — 0 errors, 0 warnings □ npx tsc --noEmit — 0 errors □ Lighthouse: Performance > 90, Accessibility > 90 □ All pages have metadata or generateMetadata □ No sensitive data in client bundle (next/bundle-analyzer) □ All Server Actions validate with Zod before DB □ loading.tsx exists for all async routes □ error.tsx exists for all critical routes


FORBIDDEN

  • NEVER use pages/api/ (use app/api/route.ts)
  • NEVER fetch data in Client Component on mount (Server Component or TanStack Query)
  • NEVER use <img> — always next/image
  • NEVER import server-only code in Client Components (use server-only package)
  • NEVER skip loading.tsx for routes with async data
  • NEVER put DB credentials in NEXT_PUBLIC_* env vars
  • NEVER use useEffect for initial data fetch (Server Component handles it)
  • NEVER call Server Actions conditionally in render (call in event handlers)
brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).Stars: 322kUpdated Claude CodeCodexVerifiedInstall
brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.Stars: 197kUpdated Claude CodeCodexVerifiedInstall
frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.Stars: 197kUpdated Claude CodeCodexVerifiedInstall
mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).Stars: 197kUpdated Claude CodeCodexVerifiedInstall