Communitygithub.com

Anhvu1107/all-agent-skill

ÚSALO SIEMPRE cuando la solicitud coincida con Nextjs Supabase Auth: Integración experta de Supabase Auth con el App Router de Next.js

¿Qué es all-agent-skill?

Esta skill proporciona una integración experta de Supabase Auth con el App Router de Next.js, ofreciendo patrones de código probados y validaciones para implementar autenticación de forma segura y eficiente. Es útil para desarrolladores que buscan configurar rápidamente flujos de autenticación (login, logout, signup, OAuth), proteger rutas con middleware, manejar callbacks de OAuth y acceder al usuario autenticado tanto en componentes del servidor como del cliente. La skill se basa en la librería `@supabase/ssr` y sigue las mejores prácticas de Next.js, incluyendo Server Actions y revalidación de caché. Además, incluye una serie de validaciones automáticas que detectan errores comunes como el uso incorrecto de `getSession()` en lugar de `getUser()`, la falta de middleware para protección de rutas, o la ausencia de manejo de errores en operaciones de autenticación. La skill colabora con otras skills como `supabase-backend` para configuración de la base de datos, `nextjs-app-router` para patrones de enrutamiento, y `vercel-deployment` para despliegue.

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

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Next.js + Supabase Auth

Regla de Lectura Selectiva

Empieza con:

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

Luego carga solo los documentos heredados, scripts, activos o ejemplos que coincidan con la tarea real del usuario.

Integración experta de Supabase Auth con el App Router de Next.js

Capacidades

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

Prerrequisitos

  • Habilidades requeridas: nextjs-app-router, supabase-backend

Patrones

Configuración del Cliente Supabase

Crear clientes Supabase correctamente configurados para diferentes contextos

Cuándo usar: Al configurar autenticación en un proyecto Next.js

// lib/supabase/client.ts (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 (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 Autenticación

Proteger rutas y refrescar sesiones en middleware

Cuándo usar: Necesitas protección de rutas o refresco de sesión

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

  // Refrescar sesión si ha expirado
  const { data: { user } } = await supabase.auth.getUser()

  // Proteger rutas del 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).*)'],
}

Ruta de Callback de Autenticación

Manejar el callback de OAuth e intercambiar el código por una sesión

Cuándo usar: Usando proveedores 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`)
}

Autenticación en Server Actions

Manejar operaciones de autenticación en Server Actions

Cuándo usar: Login, logout o signup desde 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('/')
}

Obtener Usuario en un Server Component

Acceder al usuario autenticado en Server Components

Cuándo usar: Renderizar contenido específico del usuario desde el 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>Bienvenido, {user.email}</h1>
    </div>
  )
}

Validaciones

Uso de getSession() para Verificaciones de Autenticación

Severidad: ERROR

Mensaje: getSession() no verifica el JWT. Usa getUser() para verificaciones de autenticación seguras.

Acción correctiva: Reemplaza getSession() con getUser() para verificaciones críticas de seguridad

OAuth Sin Ruta de Callback

Severidad: ERROR

Mensaje: Usando OAuth pero falta la ruta de callback en app/auth/callback/route.ts

Acción correctiva: Crea app/auth/callback/route.ts para manejar redirecciones OAuth

Cliente de Navegador en Contexto de Servidor

Severidad: ERROR

Mensaje: Cliente de navegador usado en contexto de servidor. Usa createServerClient en su lugar.

Acción correctiva: Importa y usa createServerClient desde @supabase/ssr

Rutas Protegidas Sin Middleware

Severidad: WARNING

Mensaje: No se encontró middleware.ts. Considera agregar middleware para protección de rutas.

Acción correctiva: Crea middleware.ts para proteger rutas y refrescar sesiones

URL de Redirección de Autenticación Hardcodeada

Severidad: WARNING

Mensaje: Redirección hardcodeada a localhost. Usa origin para flexibilidad según el entorno.

Acción correctiva: Usa window.location.origin o process.env.NEXT_PUBLIC_SITE_URL

Llamada de Autenticación Sin Manejo de Errores

Severidad: WARNING

Mensaje: Operación de autenticación sin manejo de errores. Siempre verifica los errores.

Acción correctiva: Desestructura { data, error } y maneja el caso de error

Acción de Autenticación Sin Revalidación

Severidad: WARNING

Mensaje: Acción de autenticación sin revalidatePath. La caché puede mostrar un estado de autenticación obsoleto.

Acción correctiva: Agrega revalidatePath('/', 'layout') después de las operaciones de autenticación

Protección de Rutas Solo en Cliente

Severidad: WARNING

Mensaje: La protección de rutas del lado del cliente muestra un destello de contenido. Usa middleware.

Acción correctiva: Mueve la protección a middleware.ts para una mejor experiencia de usuario

Colaboración

Disparadores de Delegación

  • database|rls|queries|tables -> supabase-backend (Auth necesita la capa de base de datos)
  • route|page|component|layout -> nextjs-app-router (Auth necesita patrones de Next.js)
  • deploy|production|vercel -> vercel-deployment (Auth necesita configuración de despliegue)
  • ui|form|button|design -> frontend (Auth necesita componentes de UI)

Stack Completo de Autenticación

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

Flujo de trabajo:

1. Configuración de base de datos (supabase-backend)
2. Implementación de autenticación (nextjs-supabase-auth)
3. Protección de rutas (nextjs-app-router)
4. Configuración de despliegue (vercel-deployment)

SaaS Protegido

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

Flujo de trabajo:

1. Autenticación de usuario (nextjs-supabase-auth)
2. Sincronización de clientes (stripe-integration)
3. Control de suscripciones (supabase-backend)

Habilidades Relacionadas

Funciona bien con: nextjs-app-router, supabase-backend

Cuándo Usar

  • El usuario menciona o implica: supabase auth next
  • El usuario menciona o implica: authentication next.js
  • El usuario menciona o implica: login supabase
  • El usuario menciona o implica: auth middleware
  • El usuario menciona o implica: protected route
  • El usuario menciona o implica: auth callback
  • El usuario menciona o implica: session management

Limitaciones

  • Usa esta habilidad solo cuando la tarea coincida claramente con el alcance descrito anteriormente.
  • No trates la salida como un sustituto de la validación, pruebas o revisión experta específica del entorno.
  • Detente y pide aclaraciones si faltan entradas requeridas, permisos, límites de seguridad o criterios de éxito.

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.

Skills relacionados