Communitygithub.com

ASoudy/AGS

Supabase Auth 與 Next.js App Router 的專家級整合指南

AGS 是什麼?

這個技能提供了一個完整的指南,用於在 Next.js App Router 中整合 Supabase 認證。它涵蓋了從基本的 Supabase 客戶端設置,到中間件路由保護、OAuth 回調處理、伺服器操作認證,以及在伺服器元件中獲取使用者資訊等關鍵模式。該技能特別強調了安全性最佳實踐,例如使用 `getUser()` 而不是 `getSession()` 來驗證 JWT,並提供了多種常見錯誤的驗證檢查與修復建議。支援的平台包括 Next.js 和 Supabase。透過清晰的程式碼範例和協作工作流程,開發者可以快速且安全地為其應用程式添加完整的認證功能。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ASoudy/AGS/tree/HEAD/AGAS/plugins/antigravity-awesome-skills-claude/skills/nextjs-supabase-auth

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Next.js + Supabase Auth

Supabase Auth 與 Next.js App Router 的專家級整合指南

能力

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

先決條件

  • 必備技能: nextjs-app-router, supabase-backend

模式

Supabase 客戶端設定

為不同情境建立正確配置的 Supabase 客戶端

使用時機:在 Next.js 專案中設定認證

// lib/supabase/client.ts (瀏覽器客戶端)
'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 (伺服器客戶端)
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.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)
          })
        },
      },
    }
  )

  // 如果工作階段過期則重新整理
  const { data: { user } } = await supabase.auth.getUser()

  // 保護儀表板路由
  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).*)'],
}

認證回調路由

處理 OAuth 回調並將授權碼交換為工作階段

使用時機:使用 OAuth 提供者(Google、GitHub 等)

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

伺服器動作認證

在伺服器動作中處理認證操作

使用時機:從伺服器元件登入、登出或註冊

// 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('/')
}

在伺服器元件中獲取使用者

在伺服器元件中存取已認證的使用者

使用時機:在伺服器端渲染使用者特定內容

// 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>歡迎, {user.email}</h1>
    </div>
  )
}

驗證檢查

使用 getSession() 進行認證檢查

嚴重程度:錯誤

訊息:getSession() 不會驗證 JWT。請使用 getUser() 進行安全的認證檢查。

修正動作:將 getSession() 替換為 getUser() 以進行安全關鍵檢查

缺少 OAuth 回調路由

嚴重程度:錯誤

訊息:使用 OAuth 但缺少 app/auth/callback/route.ts 回調路由

修正動作:建立 app/auth/callback/route.ts 以處理 OAuth 重定向

在伺服器環境中使用瀏覽器客戶端

嚴重程度:錯誤

訊息:在伺服器環境中使用瀏覽器客戶端。請改用 createServerClient。

修正動作:從 @supabase/ssr 匯入並使用 createServerClient

受保護路由缺少中介層

嚴重程度:警告

訊息:找不到 middleware.ts。考慮加入中介層以保護路由。

修正動作:建立 middleware.ts 以保護路由並重新整理工作階段

硬編碼的認證重定向 URL

嚴重程度:警告

訊息:硬編碼的 localhost 重定向。請使用 origin 以獲得環境靈活性。

修正動作:使用 window.location.origin 或 process.env.NEXT_PUBLIC_SITE_URL

沒有錯誤處理的認證呼叫

嚴重程度:警告

訊息:認證操作沒有錯誤處理。務必檢查錯誤。

修正動作:解構 { data, error } 並處理錯誤情況

沒有重新驗證的認證動作

嚴重程度:警告

訊息:認證動作沒有 revalidatePath。快取可能顯示過時的認證狀態。

修正動作:在認證操作後加入 revalidatePath('/', 'layout')

僅限客戶端路由保護

嚴重程度:警告

訊息:客戶端路由保護會出現內容閃現。請使用中介層。

修正動作:將保護邏輯移至 middleware.ts 以獲得更好的使用者體驗

協作

委派觸發條件

  • database|rls|queries|tables -> supabase-backend(認證需要資料庫層)
  • route|page|component|layout -> nextjs-app-router(認證需要 Next.js 模式)
  • deploy|production|vercel -> vercel-deployment(認證需要部署配置)
  • ui|form|button|design -> frontend(認證需要 UI 元件)

完整認證堆疊

技能: nextjs-supabase-auth, supabase-backend, nextjs-app-router, vercel-deployment

工作流程:

1. 資料庫設定 (supabase-backend)
2. 認證實作 (nextjs-supabase-auth)
3. 路由保護 (nextjs-app-router)
4. 部署配置 (vercel-deployment)

受保護的 SaaS

技能: nextjs-supabase-auth, stripe-integration, supabase-backend

工作流程:

1. 使用者認證 (nextjs-supabase-auth)
2. 客戶同步 (stripe-integration)
3. 訂閱閘門 (supabase-backend)

相關技能

建議搭配使用: nextjs-app-router, supabase-backend

使用時機

  • 使用者提及或暗示: supabase auth next
  • 使用者提及或暗示: authentication next.js
  • 使用者提及或暗示: login supabase
  • 使用者提及或暗示: auth middleware
  • 使用者提及或暗示: protected route
  • 使用者提及或暗示: auth callback
  • 使用者提及或暗示: session management

限制

  • 僅在任務明確符合上述範圍時使用此技能。
  • 請勿將輸出視為環境特定驗證、測試或專家審查的替代品。
  • 如果缺少必要的輸入、權限、安全邊界或成功標準,請停止並要求釐清。

Individual skills in this repo

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

ASoudy/AGS

Advanced JavaScript animation library skill for creating complex, high-performance web animations.

ASoudy/AGS

Astropy is the core Python package for astronomy, providing essential functionality for astronomical research and data analysis.

ASoudy/AGS

Build content-focused websites with Astro — zero JS by default, islands architecture, multi-framework components, and Markdown/MDX support.

ASoudy/AGS

One sentence - what this skill does and when to invoke it

ASoudy/AGS

Audit and fix animation performance issues including layout thrashing, compositor properties, scroll-linked motion, and blur effects. Use when animations stutter, transitions jank, or reviewing CSS/JS animation performance.

ASoudy/AGS

Internationalization and localization patterns. Detecting hardcoded strings, managing translations, locale files, RTL support.

ASoudy/AGS

Pull a YouTube video transcript into a queryable markdown vault with yt-dlp subtitle discovery, VTT cleanup, metadata frontmatter, and capture-seed stubs.

ASoudy/AGS

Expert in building portfolios that actually land jobs and clients - not just showing work, but creating memorable experiences. Covers developer portfolios, designer portfolios, creative portfolios, and portfolios that convert visitors into opportunities.

ASoudy/AGS

Generates high-converting Next.js/React landing pages with Tailwind CSS. Uses PAS, AIDA, and BAB frameworks for optimized copy/components (Heroes, Features, Pricing). Focuses on Core Web Vitals/SEO.

ASoudy/AGS

AI-powered animation tool for creating motion in logos, UI, icons, and social media assets.

ASoudy/AGS

CRITICAL: Use for Makepad animation system. Triggers on: makepad animation, makepad animator, makepad hover, makepad state, makepad transition, "from: { all: Forward", makepad pressed, makepad 动画, makepad 状态, makepad 过渡, makepad 悬停效果

ASoudy/AGS

Comprehensive patterns for Next.js 14+ App Router architecture, Server Components, and modern full-stack React development.

ASoudy/AGS

Next.js App Router principles. Server Components, data fetching, routing patterns.

ASoudy/AGS

React and Next.js 14+ application development with App Router, Server Components, TypeScript, Tailwind CSS, and modern frontend patterns.

ASoudy/AGS

Best practices for Remotion - Video creation in React

ASoudy/AGS

Generate walkthrough videos from Stitch projects using Remotion with smooth transitions, zooming, and text overlays

ASoudy/AGS

Seek and analyze video content using Memories.ai Large Visual Memory Model for persistent video intelligence

ASoudy/AGS

Writes complete, structured landing pages optimized for SEO ranking, AEO citation, and visitor conversion. Activate when the user wants to write or generate a landing page for a product, service, or offer.

ASoudy/AGS

Three.js animation - keyframe animation, skeletal animation, morph targets, animation mixing. Use when animating objects, playing GLTF animations, creating procedural motion, or blending animations.

ASoudy/AGS

Skill for discovering and researching autonomous AI agents, tools, and ecosystems using the AgentFolio directory.

相關技能