Communitygithub.com

ASoudy/AGS

Supabase Auth と Next.js App Router のエキスパート統合

AGS とは?

このスキルは、Next.js アプリケーションに Supabase Auth を統合するための包括的なガイドです。Next.js App Router のサーバーコンポーネントとサーバーアクションを活用し、安全で効率的な認証フローを実現します。ブラウザクライアント、サーバークライアント、ミドルウェア、コールバックルート、サーバーアクション、サーバーコンポーネントでのユーザー取得など、具体的なコードパターンを提供します。認証のセキュリティに関する検証チェック(getUser()の推奨やOAuthコールバックの欠如など)も含まれており、開発者がよくある間違いを避け、堅牢な認証システムを構築できるよう支援します。Next.js App Router と Supabase を使用するあらゆるプロジェクトに適用可能で、特にルート保護、セッション管理、OAuth 統合が必要な場面で役立ちます。

対応~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に質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

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 がありません。

修正方法: OAuth リダイレクトを処理するための app/auth/callback/route.ts を作成する

サーバーコンテキストでのブラウザクライアントの使用

重大度: エラー

メッセージ: サーバーコンテキストでブラウザクライアントが使用されています。代わりに 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') を追加する

クライアントのみのルート保護

重大度: 警告

メッセージ: クライアントサイドのルート保護では、コンテンツが一瞬表示されます。ミドルウェアを使用してください。

修正方法: より良い UX のために保護を 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.

関連スキル