TechLead
Lección 7 de 8
5 min de lectura
Supabase

Edge Functions

Escribe funciones serverless en Deno que se ejecutan cerca de tus usuarios

Supabase Edge Functions

Edge Functions son funciones serverless escritas en TypeScript que se ejecutan en Deno. Corren cerca de tus usuarios para baja latencia y pueden acceder a la base de datos, storage y auth de tu proyecto Supabase.

⚡ Características de Edge Functions

  • Runtime Deno: Entorno moderno y seguro para TypeScript
  • Edge global: Despliegue en 30+ regiones
  • Integración con Supabase: Acceso directo al proyecto
  • Webhooks: Maneja callbacks de servicios externos

Crear una Edge Function

Instalar la CLI de Supabase

# Install CLI
npm install -g supabase

# Login to Supabase
supabase login

# Initialize project (if not already)
supabase init

Crear una función

# Create new function
supabase functions new hello-world

Esto crea supabase/functions/hello-world/index.ts:

import { serve } from "https://deno.land/std@0.168.0/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" },
  })
})

Usar el cliente de Supabase

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) => {
  // Create Supabase client with service role
  const supabase = createClient(
    Deno.env.get('SUPABASE_URL') ?? '',
    Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
  )

  // Query database
  const { data, error } = await supabase
    .from('posts')
    .select('*')
    .limit(10)

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

Manejo de autenticación

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) => {
  // Get auth header
  const authHeader = req.headers.get('Authorization')!

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

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

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

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

Desarrollo local

# Start local Supabase
supabase start

# Serve functions locally
supabase functions serve hello-world --env-file .env.local

Despliegue

# Deploy a single function
supabase functions deploy hello-world

# Deploy all functions
supabase functions deploy

Invocar funciones

// From client code
const { data, error } = await supabase.functions.invoke('hello-world', {
  body: { name: 'John' }
})

// With auth (automatically includes user's JWT)
const { data, error } = await supabase.functions.invoke('protected-function', {
  body: { data: 'secure' }
})

Manejo de CORS

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

serve(async (req) => {
  // Handle CORS preflight
  if (req.method === 'OPTIONS') {
    return new Response('ok', { headers: corsHeaders })
  }

  // Your function logic
  const data = { message: 'Hello!' }

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

💡 Puntos clave

  • • Las Edge Functions se ejecutan en Deno con soporte TypeScript
  • • Usa la clave service role para operaciones de admin
  • • Pasa el JWT del usuario para solicitudes autenticadas
  • • Despliega globalmente para baja latencia

📚 Más recursos

Continuar Aprendiendo