mcpField
S
supabase-edge-functions

supabase-edge-functions

github.com/nice-wolf-studioクラウド・DevOps19358 回インストール53 週間前に更新
リポジトリ

supabase-edge-functions について

supabase-edge-functionsは、Supabase Edge Functionsを開発・運用する開発者向けのスキルです。関数の呼び出し、ローカル開発、デプロイ、ログ、テスト、認証などを扱います。

主な機能

  1. 01HTTPリクエストによる関数呼び出し
  2. 02Supabase CLIでの作成とデプロイ
  3. 03Supabaseでのローカル実行
  4. 04シークレットと認証の設定
  5. 05関数のテストとログ確認
  6. 06再試行と一括呼び出し

活用シーン

  1. 01リクエストデータやユーザートークンで関数を呼び出す
  2. 02関数をローカルで開発・テストする
  3. 03関数をデプロイしてログを確認する
  4. 04繰り返しや再試行の呼び出しを自動化する

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/nice-wolf-studio/claude-code-supabase-skills --skill supabase-edge-functions

インストール後、Claude Code で/supabase-edge-functionsを入力して読み込まれたか確認します。

詳細

Supabase Edge Functions

概要

このスキルでは、Supabase Edge Functions を操作できます。Edge Functions は Deno Deploy 上で実行される、サーバーレスの TypeScript/JavaScript 関数です。関数の呼び出し、コードのデプロイ、関数のライフサイクル管理に使用します。

前提条件

必須の環境変数:

export SUPABASE_URL="https://your-project.supabase.co"
export SUPABASE_KEY="your-anon-or-service-role-key"

必須のツール:

  • Supabase CLI(supabase コマンド)
  • Deno(ローカル開発用)

Supabase CLI のインストール:

# macOS
brew install supabase/tap/supabase

# Linux
curl -fsSL https://github.com/supabase/cli/releases/latest/download/supabase_linux_amd64.tar.gz | tar -xz
sudo mv supabase /usr/local/bin/

# Windows (PowerShell)
scoop bucket add supabase https://github.com/supabase/scoop-bucket.git
scoop install supabase

ヘルパースクリプト: このスキルでは、関数の呼び出しに共有 Supabase API ヘルパーを使用します。

source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

Edge Functions の呼び出し

基本的な呼び出し

POST で関数を呼び出す:

source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

FUNCTION_NAME="hello-world"

supabase_post "/functions/v1/${FUNCTION_NAME}" '{
  "name": "Alice"
}'

GET で呼び出す:

source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

FUNCTION_NAME="get-data"

supabase_get "/functions/v1/${FUNCTION_NAME}?id=123"
ヘッダーを指定して呼び出す

カスタムヘッダーを渡す:

FUNCTION_NAME="authenticated-function"
USER_TOKEN="user-access-token"

curl -s -X POST \
    "${SUPABASE_URL}/functions/v1/${FUNCTION_NAME}" \
    -H "apikey: ${SUPABASE_KEY}" \
    -H "Authorization: Bearer ${USER_TOKEN}" \
    -H "Content-Type: application/json" \
    -d '{"action": "process"}'
認証して呼び出す

認証済みユーザーとして関数を呼び出す:

source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

FUNCTION_NAME="user-profile"
ACCESS_TOKEN="user-jwt-token"

curl -s -X POST \
    "${SUPABASE_URL}/functions/v1/${FUNCTION_NAME}" \
    -H "apikey: ${SUPABASE_KEY}" \
    -H "Authorization: Bearer ${ACCESS_TOKEN}" \
    -H "Content-Type: application/json" \
    -d '{}'

関数の管理(CLI)

関数の初期化

新しい Edge Function を作成する:

# Navigate to your Supabase project directory
cd /path/to/project

# Create new function
supabase functions new my-function

# This creates: supabase/functions/my-function/index.ts
関数のテンプレート

基本的な関数の構成:

// supabase/functions/my-function/index.ts

import { serve } from "https://deno.land/[email protected]/http/server.ts"

serve(async (req) => {
  const { name } = await req.json()

  const data = {
    message: `Hello ${name}!`,
  }

  return new Response(
    JSON.stringify(data),
    { headers: { "Content-Type": "application/json" } },
  )
})

認証機能付きの関数:

import { serve } from "https://deno.land/[email protected]/http/server.ts"
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'

serve(async (req) => {
  // Get JWT from Authorization header
  const authHeader = req.headers.get('Authorization')!
  const token = authHeader.replace('Bearer ', '')

  // Create Supabase client with user's token
  const supabase = createClient(
    Deno.env.get('SUPABASE_URL') ?? '',
    Deno.env.get('SUPABASE_ANON_KEY') ?? '',
    { global: { headers: { Authorization: authHeader } } }
  )

  // Get authenticated user
  const { data: { user }, error } = await supabase.auth.getUser(token)

  if (error || !user) {
    return new Response('Unauthorized', { status: 401 })
  }

  return new Response(
    JSON.stringify({ message: `Hello ${user.email}!` }),
    { headers: { "Content-Type": "application/json" } },
  )
})
関数のデプロイ

Supabase に関数をデプロイする:

# Login to Supabase (first time only)
supabase login

# Link to your project (first time only)
supabase link --project-ref your-project-ref

# Deploy specific function
supabase functions deploy my-function

# Deploy with custom environment variables
supabase functions deploy my-function \
  --env-file ./supabase/.env.local

# Deploy all functions
supabase functions deploy
環境変数の設定

Edge Functions 用のシークレットを設定する:

# Set individual secret
supabase secrets set MY_SECRET_KEY=value123

# Set multiple secrets from file
# Create .env file:
# API_KEY=abc123
# DATABASE_URL=postgres://...

supabase secrets set --env-file .env

# List secrets (names only, not values)
supabase secrets list

# Unset secret
supabase secrets unset MY_SECRET_KEY
ローカル開発

関数をローカルで実行する:

# Start local Supabase (includes edge functions)
supabase start

# Serve functions locally
supabase functions serve

# Serve specific function
supabase functions serve my-function --env-file ./supabase/.env.local

# Invoke local function
curl http://localhost:54321/functions/v1/my-function \
  -H "Authorization: Bearer ${SUPABASE_KEY}" \
  -d '{"name": "test"}'
関数の削除

デプロイ済みの関数を削除する:

# Delete function from Supabase dashboard or using SQL
# Note: No direct CLI command to delete, must use dashboard

# Remove local function file
rm -rf supabase/functions/my-function

一般的なパターン

関数を呼び出してレスポンスを処理する
#!/bin/bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

FUNCTION_NAME="process-data"

response=$(supabase_post "/functions/v1/${FUNCTION_NAME}" '{
  "action": "calculate",
  "values": [1, 2, 3, 4, 5]
}')

if [[ $? -eq 0 ]]; then
    result=$(echo "$response" | jq -r '.result')
    echo "Function result: $result"
else
    echo "Function invocation failed"
    exit 1
fi
複数の関数を一括で呼び出す
#!/bin/bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

FUNCTION_NAME="send-email"
RECIPIENTS=("[email protected]" "[email protected]" "[email protected]")

for email in "${RECIPIENTS[@]}"; do
    echo "Processing $email..."

    supabase_post "/functions/v1/${FUNCTION_NAME}" '{
      "to": "'"$email"'",
      "subject": "Hello",
      "body": "Test message"
    }'

    echo "✓ Sent to $email"
done
再試行ロジックを備えた関数
#!/bin/bash
source "$(dirname "${BASH_SOURCE[0]}")/../../scripts/supabase-api.sh"

invoke_with_retry() {
    local function_name="$1"
    local payload="$2"
    local max_retries=3
    local retry_count=0

    while [[ $retry_count -lt $max_retries ]]; do
        if response=$(supabase_post "/functions/v1/${function_name}" "$payload" 2>&1); then
            echo "$response"
            return 0
        else
            retry_count=$((retry_count + 1))
            echo "Retry $retry_count/$max_retries..." >&2
            sleep 2
        fi
    done

    echo "Function failed after $max_retries retries" >&2
    return 1
}

# Use it
invoke_with_retry "my-function" '{"action": "process"}'
関数のデプロイスクリプト
#!/bin/bash
# deploy-function.sh

FUNCTION_NAME="${1:-my-function}"

echo "Deploying function: $FUNCTION_NAME"

# Validate function exists
if [[ ! -d "supabase/functions/$FUNCTION_NAME" ]]; then
    echo "Error: Function $FUNCTION_NAME not found"
    exit 1
fi

# Deploy
if supabase functions deploy "$FUNCTION_NAME"; then
    echo "✓ Deployed successfully"

    # Test invocation
    echo "Testing function..."
    response=$(curl -s -X POST \
        "${SUPABASE_URL}/functions/v1/${FUNCTION_NAME}" \
        -H "apikey: ${SUPABASE_KEY}" \
        -H "Content-Type: application/json" \
        -d '{}')

    echo "Test response: $response"
else
    echo "✗ Deployment failed"
    exit 1
fi
関数ログの監視
# View function logs (requires Supabase CLI)
supabase functions logs my-function

# Follow logs in real-time
supabase functions logs my-function --follow

# Filter logs by level
supabase functions logs my-function --level error

# View logs from specific time
supabase functions logs my-function --since 1h

高度なパターン

データベースにアクセスする関数
// supabase/functions/get-user-data/index.ts
import { serve } from "https://deno.land/[email protected]/http/server.ts"
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'

serve(async (req) => {
  const supabase = createClient(
    Deno.env.get('SUPABASE_URL') ?? '',
    Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
  )

  const { userId } = await req.json()

  const { data, error } = await supabase
    .from('users')
    .select('*')
    .eq('id', userId)
    .single()

  if (error) {
    return new Response(JSON.stringify({ error: error.message }), {
      status: 400,
      headers: { 'Content-Type': 'application/json' }
    })
  }

  return new Response(JSON.stringify(data), {
    headers: { 'Content-Type': 'application/json' }
  })
})
外部 API を呼び出す関数
// supabase/functions/fetch-weather/index.ts
import { serve } from "https://deno.land/[email protected]/http/server.ts"

serve(async (req) => {
  const { city } = await req.json()
  const apiKey = Deno.env.get('WEATHER_API_KEY')

  const response = await fetch(
    `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`
  )

  const data = await response.json()

  return new Response(JSON.stringify(data), {
    headers: { 'Content-Type': 'application/json' }
  })
})
スケジュール実行関数(Cron)
// supabase/functions/daily-cleanup/index.ts
import { serve } from "https://deno.land/[email protected]/http/server.ts"
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2'

serve(async (req) => {
  // Verify request is from Supabase Cron
  const authHeader = req.headers.get('Authorization')
  if (authHeader !== `Bearer ${Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')}`) {
    return new Response('Unauthorized', { status: 401 })
  }

  const supabase = createClient(
    Deno.env.get('SUPABASE_URL') ?? '',
    Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
  )

  // Delete old records
  const { data, error } = await supabase
    .from('logs')
    .delete()
    .lt('created_at', new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString())

  return new Response(JSON.stringify({ deleted: data?.length ?? 0 }), {
    headers: { 'Content-Type': 'application/json' }
  })
})

Supabase ダッシュボードで cron ジョブを設定する:

-- In SQL Editor, create pg_cron job:
select cron.schedule(
  'daily-cleanup',
  '0 2 * * *', -- Run at 2 AM daily
  $$
  select
    net.http_post(
      url := 'https://your-project.supabase.co/functions/v1/daily-cleanup',
      headers := '{"Content-Type": "application/json", "Authorization": "Bearer YOUR_SERVICE_ROLE_KEY"}'::jsonb,
      body := '{}'::jsonb
    ) as request_id;
  $$
);

関数のテスト

ローカルでテストする
# Start local environment
supabase start

# Serve function
supabase functions serve my-function

# Test with curl
curl http://localhost:54321/functions/v1/my-function \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -d '{"test": "data"}'
統合テストスクリプト
#!/bin/bash
# test-function.sh

FUNCTION_NAME="$1"
TEST_CASES_FILE="$2"

if [[ ! -f "$TEST_CASES_FILE" ]]; then
    echo "Test cases file not found"
    exit 1
fi

echo "Testing function: $FUNCTION_NAME"

while IFS= read -r test_case; do
    echo "Test case: $test_case"

    response=$(curl -s -X POST \
        "${SUPABASE_URL}/functions/v1/${FUNCTION_NAME}" \
        -H "apikey: ${SUPABASE_KEY}" \
        -H "Content-Type: application/json" \
        -d "$test_case")

    echo "Response: $response"
    echo "---"
done < "$TEST_CASES_FILE"

エラー処理

関数のエラーは HTTP ステータスコードで返されます:

ステータス意味
200成功
400不正なリクエスト(入力が無効)
401認証されていない(認証が無効または不足)
403アクセス禁止(権限が不足)
500内部サーバーエラー(関数のクラッシュ)
504ゲートウェイタイムアウト(関数の実行時間が長すぎる)

タイムアウト制限: Edge Functions の CPU 時間制限は 2 秒、実時間のタイムアウトは 150 秒です。

セキュリティのベストプラクティス

  1. 入力の検証:リクエストデータは必ず検証してサニタイズしてください
  2. サービスロールキーの慎重な使用:管理者向け関数でのみ使用し、クライアントには決して公開しないでください
  3. 認証の実装:保護対象の関数ではユーザートークンを確認してください
  4. レート制限:公開関数にはレート制限を実装してください
  5. 環境変数:シークレットはコード内ではなく、Supabase のシークレットに保存してください
  6. CORS:CORS ヘッダーを適切に設定してください
  7. エラーメッセージ:エラーレスポンスで機密情報を漏らさないでください

パフォーマンスのヒント

  1. コールドスタート:関数ではコールドスタートが発生する場合があります(100~200 ms の遅延)
  2. 関数を小さく保つ:コールドスタートが速くなり、デバッグも容易になります
  3. 外部データのキャッシュ:API 呼び出しを繰り返す場合は、メモリ内キャッシュを使用してください
  4. 並列実行:同時処理には Promise.all() を使用してください
  5. 大きなレスポンスのストリーミング:大容量のデータ転送にはストリーミングを使用してください

API ドキュメント

コメント