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.
Customize & Generate Your Prompt
Adjust the variables below. Your customized prompt updates live in real-time ready to copy with zero setup.
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
- 1Paste your Deno Edge Function code and the exact error log received in the terminal or browser console.
- 2Select the intended authorization mode (e.g. Bearer JWT vs Webhook signature).
- 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.
Related Tools on SPAUL Hub
More in Developers & Coding
View CategoryNext.js App Router Project Rules & AI Coding Agent Instructions
A comprehensive system prompt that transforms AI coding assistants (Claude 3.7, Cursor, ChatGPT, Gemini) into disciplined Next.js App Router architects. Prevents common hydration traps and enforce strict separation between Server and Client Components.
React Component Refactoring & Unit Test Generation Prompt
Turn bloated, legacy React components with tangled state into modular, accessible, and high-performance components backed by a production-ready test suite.
AI Coding Agent Codebase Audit & Modernization Prompt
A structured audit prompt designed for AI coding agents to evaluate an unfamiliar codebase, identify security anti-patterns, spot performance bottlenecks, and generate prioritized action plans.