惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
腾讯CDC
Jina AI
Jina AI
博客园 - 司徒正美
博客园 - 三生石上(FineUI控件)
Apple Machine Learning Research
Apple Machine Learning Research
GbyAI
GbyAI
WordPress大学
WordPress大学
Hugging Face - Blog
Hugging Face - Blog
T
The Blog of Author Tim Ferriss
小众软件
小众软件
M
MIT News - Artificial intelligence
MyScale Blog
MyScale Blog
D
Docker
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Google DeepMind News
Google DeepMind News
月光博客
月光博客
L
LangChain Blog
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - Franky
C
Check Point Blog
U
Unit 42
人人都是产品经理
人人都是产品经理

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Supabase Edge Functions Complete Guide — Serverless APIs ...
kanta13jp1 · 2026-04-29 · via DEV Community

kanta13jp1

Supabase Edge Functions Complete Guide — Serverless APIs with Deno & TypeScript

Supabase Edge Functions run on the Deno runtime at the global edge. Native TypeScript, fast cold starts, and seamless Supabase integration make them the ideal serverless layer for Flutter apps.

Why Edge Functions?

  • Deno runtime: Web-standard APIs, not Node.js
  • TypeScript native: No transpile step
  • Global edge: Runs close to your users
  • Env vars: Deno.env.get('VAR_NAME')
  • Cold start: Under 50ms (faster than Lambda)

Local Development

npm install -g supabase
supabase start
supabase functions serve --env-file .env.local
supabase functions new my-function

Enter fullscreen mode Exit fullscreen mode

Basic Function Structure

// supabase/functions/my-function/index.ts
import { createClient } from 'npm:@supabase/supabase-js@2'

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

Deno.serve(async (req: Request) => {
  if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders })

  try {
    const authHeader = req.headers.get('Authorization')
    if (!authHeader) return new Response(
      JSON.stringify({ error: 'Unauthorized' }),
      { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )

    const supabase = createClient(
      Deno.env.get('SUPABASE_URL')!,
      Deno.env.get('SUPABASE_ANON_KEY')!,
      { global: { headers: { Authorization: authHeader } } }
    )

    const { data: { user }, error } = await supabase.auth.getUser()
    if (error || !user) return new Response(
      JSON.stringify({ error: 'Invalid token' }),
      { status: 401, headers: { ...corsHeaders, 'Content-Type': 'application/json' } }
    )

    const { message } = await req.json()
    const result = await processMessage(supabase, user.id, message)

    return new Response(JSON.stringify({ data: result }), {
      headers: { ...corsHeaders, 'Content-Type': 'application/json' }
    })
  } catch (error) {
    return new Response(JSON.stringify({ error: error.message }), {
      status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' }
    })
  }
})

Enter fullscreen mode Exit fullscreen mode

Hub Pattern (Stay Under the 50 EF Limit)

Route multiple actions through one EF:

// supabase/functions/schedule-hub/index.ts
type Action = 'digest.run' | 'metrics.get' | 'notifications.send' | 'competitor.check'

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

  const { action, payload } = await req.json()

  switch (action) {
    case 'digest.run': return handleDigest(payload)
    case 'metrics.get': return handleMetrics(payload)
    case 'notifications.send': return handleNotifications(payload)
    case 'competitor.check': return handleCompetitorCheck(payload)
    default: return new Response(
      JSON.stringify({ error: `Unknown action: ${action}` }),
      { status: 400, headers: corsHeaders }
    )
  }
})

Enter fullscreen mode Exit fullscreen mode

External API Integration

async function callOpenAI(prompt: string): Promise<string> {
  const res = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${Deno.env.get('OPENAI_API_KEY')}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      model: 'gpt-4o-mini',
      messages: [{ role: 'user', content: prompt }],
      max_tokens: 500,
    }),
  })
  const data = await res.json()
  return data.choices[0].message.content
}

Enter fullscreen mode Exit fullscreen mode

Deploy

supabase functions deploy my-function
supabase functions deploy  # Deploy all
supabase secrets set OPENAI_API_KEY=sk-...
supabase secrets set RESEND_API_KEY=re_...

Enter fullscreen mode Exit fullscreen mode

Calling from Flutter

class EdgeFunctionService {
  static Future<Map<String, dynamic>> callHub({
    required String action,
    Map<String, dynamic>? payload,
  }) async {
    final response = await supabase.functions.invoke(
      'schedule-hub',
      body: {'action': action, 'payload': payload},
    );
    if (response.status != 200) throw Exception('EF Error: ${response.data['error']}');
    return response.data as Map<String, dynamic>;
  }
}

// Usage
final metrics = await EdgeFunctionService.callHub(action: 'metrics.get');

Enter fullscreen mode Exit fullscreen mode

Structured Logging

console.log(JSON.stringify({
  level: 'info',
  action: 'digest.run',
  userId: user.id,
  duration_ms: Date.now() - startTime,
}))

Enter fullscreen mode Exit fullscreen mode

Summary

The Hub pattern lets you consolidate multiple actions into one Edge Function, keeping you well under Supabase's 50 EF limit. Deno's Web-standard APIs and native TypeScript make for clean, maintainable serverless code.


Building an AI Life Management app with Flutter × Supabase at 自分株式会社. Sharing indie dev insights every week.