Supabase Edge Functions

SUPABASEDENOSERVERLESS

Supabase is a perfect backend for modern apps, but user generated content needs guardrails. Using Database Webhooks and Edge Functions, you can automatically scan every row inserted into your database without changing your frontend code.

01. CREATE FUNCTION

Generate a new function using the Supabase CLI:

supabase functions new moderate-content

02. IMPLEMENTATION

Edit `supabase/functions/moderate-content/index.ts`:

import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { SafeComms } from "npm:@safecomms/sdk";

// Initialize with environment variables
const safecomms = new SafeComms({ apiKey: Deno.env.get('SAFECOMMS_API_KEY') });

serve(async (req) => {
  try {
    // 1. > PARSE_WEBHOOK_PAYLOAD
    // Assuming this is triggered by a database webhook (e.g. INSERT into 'comments' table)
    const payload = await req.json();
    const { record } = payload;

    if (!record || !record.content) {
      return new Response("No content to analyze", { status: 200 });
    }

    console.log(`> ANALYZING_RECORD: ${record.id}`);

    // 2. > CALL_SAFECOMMS_API
    const analysis = await safecomms.text.analyze({
      content: record.content
    });

    // 3. > REACT_TO_THREATS
    if (analysis.flagged) {
      console.log(`> FLAGGED: ${analysis.primaryCategory}`);

      // Option A: Delete the record immediately using Supabase Admin Client
      /*
      const supabase = createClient(..);
      await supabase.from('comments').delete().eq('id', record.id);
      */

      // Option B: Flag it for review (Update 'status' column)
      return new Response(JSON.stringify({
        action: 'flagged',
        reason: analysis.primaryCategory
      }), {
        headers: { "Content-Type": "application/json" }
      });
    }

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

  } catch (error) {
    console.error('> EDGE_FUNCTION_ERROR:', error);
    return new Response(JSON.stringify({ error: error.message }), { status: 500 });
  }
});

> TRIGGER_CONFIGURATION

Don't forget to configure the Database Webhook in the Supabase Dashboard! Go to Database > Webhooks > Create Webhook, select the table (e.g., `comments`), check `INSERT`, and point it to your Edge Function URL.