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 This Prompt Effectively

  1. 1Paste your Deno Edge Function code and the exact error log received in the terminal or browser console.
  2. 2Select the intended authorization mode (e.g. Bearer JWT vs Webhook signature).
  3. 3Submit 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.