Communitygithub.com

Anhvu1107/all-agent-skill

Sempre use esta skill quando a solicitação corresponder à combinação Next.js + Supabase Auth: Integração especializada do Supabase Auth com o App Router do Next.js

O que é all-agent-skill?

Esta skill fornece integração especializada do Supabase Auth com o Next.js App Router. Ela configura corretamente clientes Supabase para diferentes contextos (navegador e servidor), implementa middleware para proteção de rotas e renovação de sessão, gerencia callbacks OAuth e oferece operações de autenticação em Server Actions e componentes de servidor. A skill inclui validações rigorosas, como alertas sobre o uso de `getSession()` em vez de `getUser()` para verificação segura de autenticação, sobre rotas protegidas sem middleware e sobre a falta de tratamento de erros em operações de auth. Ela colabora com skills como `supabase-backend`, `nextjs-app-router` e `vercel-deployment` para um fluxo completo de autenticação, e é particularmente útil em stacks protegidas ou SaaS, onde também se integra com Stripe para gerenciamento de assinaturas.

Funciona com~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Anhvu1107/all-agent-skill/tree/HEAD/.agent/skills/nextjs-supabase-auth

Perguntar na sua IA favorita

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

Documentação

Next.js + Supabase Auth

Regra de Leitura Seletiva

Comece com:

  • references/senior-master-standard.md
  • references/usage-routing.md
  • references/quality-checklist.md

Em seguida, carregue apenas os documentos, scripts, assets ou exemplos herdados que correspondam à tarefa real do usuário.

Integração especializada do Supabase Auth com o App Router do Next.js

Capacidades

  • nextjs-auth
  • supabase-auth-nextjs
  • auth-middleware
  • auth-callback

Pré-requisitos

  • Skills necessárias: nextjs-app-router, supabase-backend

Padrões

Configuração do Cliente Supabase

Crie clientes Supabase configurados corretamente para diferentes contextos

Quando usar: Configurando auth em um projeto Next.js

// lib/supabase/client.ts (Cliente do navegador)
'use client'
import { createBrowserClient } from '@supabase/ssr'

export function createClient() {
  return createBrowserClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
  )
}

// lib/supabase/server.ts (Cliente do servidor)
import { createServerClient } from '@supabase/ssr'
import { cookies } from 'next/headers'

export async function createClient() {
  const cookieStore = await cookies()
  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll() {
          return cookieStore.getAll()
        },
        setAll(cookiesToSet) {
          cookiesToSet.forEach(({ name, value, options }) => {
            cookieStore.set(name, value, options)
          })
        },
      },
    }
  )
}

Middleware de Auth

Proteja rotas e renove sessões no middleware

Quando usar: Você precisa de proteção de rotas ou renovação de sessão

// middleware.ts
import { createServerClient } from '@supabase/ssr'
import { NextResponse, type NextRequest } from 'next/server'

export async function middleware(request: NextRequest) {
  let response = NextResponse.next({ request })

  const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll() {
          return request.cookies.getAll()
        },
        setAll(cookiesToSet) {
          cookiesToSet.forEach(({ name, value, options }) => {
            response.cookies.set(name, value, options)
          })
        },
      },
    }
  )

  // Renova a sessão se expirada
  const { data: { user } } = await supabase.auth.getUser()

  // Protege rotas do dashboard
  if (request.nextUrl.pathname.startsWith('/dashboard') && !user) {
    return NextResponse.redirect(new URL('/login', request.url))
  }

  return response
}

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
}

Rota de Callback de Auth

Lida com o callback OAuth e troca o código por uma sessão

Quando usar: Usando provedores OAuth (Google, GitHub, etc.)

// app/auth/callback/route.ts
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'

export async function GET(request: Request) {
  const { searchParams, origin } = new URL(request.url)
  const code = searchParams.get('code')
  const next = searchParams.get('next') ?? '/'

  if (code) {
    const supabase = await createClient()
    const { error } = await supabase.auth.exchangeCodeForSession(code)
    if (!error) {
      return NextResponse.redirect(`${origin}${next}`)
    }
  }

  return NextResponse.redirect(`${origin}/auth/error`)
}

Auth em Server Actions

Lida com operações de auth em Server Actions

Quando usar: Login, logout ou cadastro a partir de Server Components

// app/actions/auth.ts
'use server'
import { createClient } from '@/lib/supabase/server'
import { redirect } from 'next/navigation'
import { revalidatePath } from 'next/cache'

export async function signIn(formData: FormData) {
  const supabase = await createClient()
  const { error } = await supabase.auth.signInWithPassword({
    email: formData.get('email') as string,
    password: formData.get('password') as string,
  })

  if (error) {
    return { error: error.message }
  }

  revalidatePath('/', 'layout')
  redirect('/dashboard')
}

export async function signOut() {
  const supabase = await createClient()
  await supabase.auth.signOut()
  revalidatePath('/', 'layout')
  redirect('/')
}

Obter Usuário em Server Component

Acesse o usuário autenticado em Server Components

Quando usar: Renderizando conteúdo específico do usuário no lado do servidor

// app/dashboard/page.tsx
import { createClient } from '@/lib/supabase/server'
import { redirect } from 'next/navigation'

export default async function DashboardPage() {
  const supabase = await createClient()
  const { data: { user } } = await supabase.auth.getUser()

  if (!user) {
    redirect('/login')
  }

  return (
    <div>
      <h1>Welcome, {user.email}</h1>
    </div>
  )
}

Verificações de Validação

Usando getSession() para verificações de auth

Severidade: ERRO

Mensagem: getSession() não verifica o JWT. Use getUser() para verificações de auth seguras.

Ação de correção: Substitua getSession() por getUser() para verificações críticas de segurança

OAuth sem Rota de Callback

Severidade: ERRO

Mensagem: Usando OAuth, mas faltando a rota de callback em app/auth/callback/route.ts

Ação de correção: Crie app/auth/callback/route.ts para lidar com redirecionamentos OAuth

Cliente do Navegador em Contexto de Servidor

Severidade: ERRO

Mensagem: Cliente do navegador usado em contexto de servidor. Use createServerClient.

Ação de correção: Importe e use createServerClient de @supabase/ssr

Rotas Protegidas sem Middleware

Severidade: AVISO

Mensagem: Nenhum middleware.ts encontrado. Considere adicionar middleware para proteção de rotas.

Ação de correção: Crie middleware.ts para proteger rotas e renovar sessões

URL de Redirecionamento de Auth Fixa

Severidade: AVISO

Mensagem: Redirecionamento localhost fixo no código. Use origin para flexibilidade de ambiente.

Ação de correção: Use window.location.origin ou process.env.NEXT_PUBLIC_SITE_URL

Chamada de Auth sem Tratamento de Erros

Severidade: AVISO

Mensagem: Operação de auth sem tratamento de erros. Sempre verifique erros.

Ação de correção: Desestruture { data, error } e trate o caso de erro

Ação de Auth sem Revalidação

Severidade: AVISO

Mensagem: Ação de auth sem revalidatePath. O cache pode mostrar estado de auth desatualizado.

Ação de correção: Adicione revalidatePath('/', 'layout') após operações de auth

Proteção de Rota Apenas no Cliente

Severidade: AVISO

Mensagem: Proteção de rota no lado do cliente mostra um flash de conteúdo. Use middleware.

Ação de correção: Mova a proteção para middleware.ts para melhor UX

Colaboração

Gatilhos de Delegação

  • database|rls|queries|tables -> supabase-backend (Auth precisa da camada de banco de dados)
  • route|page|component|layout -> nextjs-app-router (Auth precisa de padrões Next.js)
  • deploy|production|vercel -> vercel-deployment (Auth precisa de configuração de deploy)
  • ui|form|button|design -> frontend (Auth precisa de componentes de UI)

Stack Completa de Auth

Skills: nextjs-supabase-auth, supabase-backend, nextjs-app-router, vercel-deployment

Fluxo de trabalho:

1. Configuração do banco de dados (supabase-backend)
2. Implementação de Auth (nextjs-supabase-auth)
3. Proteção de rotas (nextjs-app-router)
4. Configuração de deploy (vercel-deployment)

SaaS Protegido

Skills: nextjs-supabase-auth, stripe-integration, supabase-backend

Fluxo de trabalho:

1. Autenticação do usuário (nextjs-supabase-auth)
2. Sincronização de clientes (stripe-integration)
3. Gerenciamento de assinaturas (supabase-backend)

Skills Relacionadas

Funciona bem com: nextjs-app-router, supabase-backend

Quando Usar

  • O usuário menciona ou sugere: supabase auth next
  • O usuário menciona ou sugere: authentication next.js
  • O usuário menciona ou sugere: login supabase
  • O usuário menciona ou sugere: auth middleware
  • O usuário menciona ou sugere: protected route
  • O usuário menciona ou sugere: auth callback
  • O usuário menciona ou sugere: session management

Limitações

  • Use esta skill apenas quando a tarefa corresponder claramente ao escopo descrito acima.
  • Não trate o resultado como substituto para validação específica de ambiente, testes ou revisão especializada.
  • Pare e peça esclarecimentos se as entradas necessárias, permissões, limites de segurança ou critérios de sucesso estiverem ausentes.

Individual skills in this repo

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

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches 007: Security audit, hardening, threat modeling (STRIDE/PASTA), Red/Blue Team, OWASP checks, code review, incident response, and infrastructure security for any project.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Agentfolio: Skill for discovering and researching autonomous AI agents, tools, and ecosystems using the AgentFolio directory.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Animejs Animation: Advanced JavaScript animation library skill for creating complex, high-performance web animations.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Astropy: Astropy is the core Python package for astronomy, providing essential functionality for astronomical research and data analysis.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Astro: Build content-focused websites with Astro — zero JS by default, islands architecture, multi-framework components, and Markdown/MDX support.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Emotional ARC Designer: One sentence - what this skill does and when to invoke it

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Fixing Motion Performance: Audit and fix animation performance issues including layout thrashing, compositor properties, scroll-linked motion, and blur effects.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches I18n Localization: Internationalization and localization patterns.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Interactive Portfolio: Expert in building portfolios that actually land jobs and clients - not just showing work, but creating memorable experiences.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches JQ: Expert jq usage for JSON querying, filtering, transformation, and pipeline integration.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Landing Page Generator: Generates high-converting Next.js/React landing pages with Tailwind CSS.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches LEX: Centralized ''Truth Engine'' for cross-jurisdictional legal context (US, EU, CA) and contract scaffolding.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Magic Animator: AI-powered animation tool for creating motion in logos, UI, icons, and social media assets.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Makepad Animation: CRITICAL: Use for Makepad animation system.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches Nextjs APP Router Patterns: Comprehensive patterns for Next.js 14+ App Router architecture, Server Components, and modern full-stack React development.

Anhvu1107/all-agent-skill

ALWAYS use this when the user mentions Nextjs Best Practices, asks to build, debug, review, document, automate, test, configure, migrate, or make decisions in this domain, or the task clearly depends on Nextjs Best Practices; scope: Next.js App Router principles. Apply the bundled workflow, references, scripts, Senior Master standard, and Codex strict review gate before final output.

Anhvu1107/all-agent-skill

description: ALWAYS use this when the work is specifically about modern Next.js or React architecture, data flow, rendering strategy, routing, or performance-sensitive frontend behavior.

Anhvu1107/all-agent-skill

ALWAYS use this when the task involves reading, extracting, splitting, merging, rotating, creating, validating, OCR-ing, form-filling, or otherwise producing or modifying PDF files.

Anhvu1107/all-agent-skill

ALWAYS use this when the request matches React Nextjs Development: React and Next.js 14+ application development with App Router, Server Components, TypeScript, Tailwind CSS, and modern frontend patterns.

Anhvu1107/all-agent-skill

ALWAYS use this when working with Remotion code, video compositions, rendering logic, timing, media assets, or React-based motion workflows.

Habilidades Relacionadas