Developers & CodingUpdated October 2026

Supabase Edge Function Debugging & Security Review

Diagnose runtime errors, CORS header issues, environment variable leakage, and authentication token validation bugs in Supabase Deno Edge Functions.

Target Users: Backend Developers, Full-Stack Engineers, and DevOps Specialists
Supported Workflow: Bug triage, security audits of serverless functions, and local Supabase CLI simulation
Interactive Prompt Builder

Customize & Generate Your Prompt

Adjust the variables below. Your customized prompt updates live in real-time ready to copy with zero setup.

Input Variables (4)runs 100% locally
System / Role Prompt
You are a senior cloud infrastructure engineer specializing in Deno runtimes, Supabase Edge Functions, and JWT authorization standards. You identify subtle edge deployment pitfalls, memory leaks, and authorization oversights.
Assembled User Prompt (Live Preview)1955 chars
Please conduct a thorough technical diagnosis and security review of this Supabase Edge Function.

### Function Details
- **Function Name**: process-payment-webhook
- **Authorization Model**: Authenticated User (JWT / Bearer Token via RLS)
- **Observed Error / Problem**:
```text
Failed to send request: TypeError: Cannot read properties of undefined (reading "id") at server.ts:24. Browser console also reports: Access to fetch blocked by CORS policy: Response to preflight request doesn't pass access control check.
```

### Function Source Code
```typescript
import { serve } from "https://deno.land/std@0.168.0/http/server.ts"
import { createClient } from "https://esm.sh/@supabase/supabase-js@2"

serve(async (req) => {
  const { userId, planId } = await req.json()
  const supabase = createClient(
    Deno.env.get('SUPABASE_URL') ?? '',
    Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
  )
  const { data, error } = await supabase.from('profiles').select('*').eq('id', userId).single()
  return new Response(JSON.stringify(data), { headers: { "Content-Type": "application/json" } })
})
```

### Required Review Deliverables
1. **Root-Cause Analysis**: Explain precisely why the error occurred in the Deno runtime environment.
2. **CORS & Preflight Verification**: Verify whether `OPTIONS` preflight headers and standard response headers adhere to browser security specifications.
3. **Authentication & Authorization Check**:
   - Does the function properly verify the user's `Authorization: Bearer <token>` header?
   - Is the service role key (`SUPABASE_SERVICE_ROLE_KEY`) exposed to the client or used unnecessarily where RLS would suffice?
4. **Refactored Code**: Provide the clean, idiomatic TypeScript source code with explicit error handling, typed response wrappers, and graceful fallbacks.
5. **Local Testing Command**: Provide the exact `supabase functions serve` CLI invocation to test this locally with dummy payload and mock headers.

How to Use & Customize This Prompt

Step 1: Customize Inputs

Fill in your target framework, environment rules, or source metrics in the interactive builder above. The assembled template updates instantly.

Step 2: Copy Assembled Prompt

Click "Copy Prompt to Clipboard". You can copy the full assembled text or copy system instructions separately.

Step 3: Select Recommended AI Model

Refer to the Model Guidance below to choose the highest-performing frontier model or local runtime for this specific task.

Step 4: Execute & Verify Output

Paste into your AI coding tool, chat interface, or local Ollama runtime. Verify syntax, types, and schema compliance against expected output.

Workflow Guidance

  • Paste your Deno Edge Function code and the exact error log received in the terminal or browser console.
  • Select the intended authorization mode (e.g. Bearer JWT vs Webhook signature).
  • Submit the prompt to your AI model to obtain a patched script with correct CORS headers and secure client initialization.

Representative AI Output

Sample output produced when using frontier AI models with the default parameters:

### Issue Analysis
1. **Missing Preflight Handler**: Modern browsers dispatch an HTTP `OPTIONS` request prior to sending a `POST` with custom headers. When your handler attempts to run `req.json()` on an OPTIONS request, it crashes or fails to return CORS headers.
2. **Missing In-Flight Token Verification**: Initializing the Supabase client with `SUPABASE_SERVICE_ROLE_KEY` bypasses Row Level Security (RLS) entirely, enabling unauthenticated callers to query any profile if they spoof `userId`.

### Recommended Patch
```typescript
import { serve } from "https://deno.land/std@0.168.0/http/server.ts"
import { createClient } from "https://esm.sh/@supabase/supabase-js@2"

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}

serve(async (req) => {
  if (req.method === 'OPTIONS') {
    return new Response('ok', { headers: corsHeaders })
  }
  // Safe execution with client authentication...
})
```

Pro Optimization & Edge-Case Tips

  • Never export your service role key to frontend bundles. If an edge function only needs the authenticated user context, initialize the Supabase client with the user JWT.
  • Always handle `req.method === "OPTIONS"` at the very top of your handler before any body parsing or database calls.
  • Use `deno check` or `supabase functions serve --no-verify-jwt` during local development to catch type errors before deploying.
Recommended AI Models

Recommended AI Models for Coding & Full-Stack Engineering

Frontier models tested against Next.js 15, TypeScript 5.6, Supabase, and automated unit test generation.

Claude 3.5 Sonnet

Top Pick for Architecture & Refactoring

Deep codebase reasoning, complex Next.js App Router rules, and full test suites without omissions.

Key Strengths
  • Unrivaled understanding of modern React 19 / Next.js Server Components
  • Strict compliance with system instructions without skipping edge-case checks
  • Generates syntactically complete Vitest and RTL mocks
Pro Tip: Paste prompt as Project Instructions or Artifact System Prompt for strict adherence.

OpenAI GPT-4o

High Speed & Tool Calling

Rapid iterative debugging, Supabase function logging, and strict JSON output schemas.

Key Strengths
  • Sub-second first-token latency for fast dev loops
  • Excellent function-calling and schema validation reliability
  • Accurate regex generation and API endpoint routing
Pro Tip: Enable Structured Outputs mode when parsing raw terminal logs or compiler errors.

DeepSeek-Coder V2

Open Weights & Cost Efficiency

Local inference and budget-friendly batch refactoring across large file trees.

Key Strengths
  • 236B MoE architecture competitive with proprietary frontier models
  • Strong 128K context window for multi-file dependency trees
  • Available via Ollama and vLLM for self-hosted private workflows
Pro Tip: Use temperature 0.1 to maximize deterministic code output and minimize syntax drift.
Test Prompts in SPAUL AI Studio

Copy your assembled prompt and test immediately with approved frontier models or your own API key.

Open AI Chat