Supabase Edge Functions 是一個基於 Deno 運行時的無伺服器函數服務,可以在邊緣節點執行,TypeScript/JavaScript 程式碼。這些函數會在全球各地的邊緣伺服器上運行,確保低延遲和高效能。
想像 Edge Functions 就像是何振宇的「影子軍團」:
# 建立名為 hello-world 的函數
supabase functions new hello-world
這會在 supabase/functions/hello-world/index.ts
建立一個基本的函數模板:
import 'jsr:@supabase/functions-js/edge-runtime.d.ts';
console.log('Hello from Functions!');
Deno.serve(async req => {
const { name } = await req.json();
const data = {
message: `Hello ${name}!`,
};
return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } });
});
# 啟動本地開發環境
supabase start
# 在另一個終端機中提供函數服務
supabase functions serve hello-world
curl -i --location --request POST 'http://localhost:54321/functions/v1/hello-world' \
--header 'Authorization: Bearer YOUR_ANON_KEY' \
--header 'Content-Type: application/json' \
--data '{"name":"Functions"}'
# 部署函數
supabase functions deploy hello-world
# 部署到雲端特定專案
supabase functions deploy hello-world --project-ref your-project-ref
hello-world
)在線上編輯器中輸入:
import 'jsr:@supabase/functions-js/edge-runtime.d.ts';
interface reqPayload {
name: string;
}
console.info('server started');
Deno.serve(async (req: Request) => {
const { name }: reqPayload = await req.json();
const data = {
message: `Hello ${name}!`,
};
return new Response(JSON.stringify(data), {
headers: { 'Content-Type': 'application/json', Connection: 'keep-alive' },
});
});
在 Dashboard 的測試區域中(點擊進入剛剛建立的函數內頁,右上角「Test」):
{
"name": "World"
}
import { createClient } from '@supabase/supabase-js';
const supabase = createClient('YOUR_SUPABASE_URL', 'YOUR_SUPABASE_ANON_KEY');
// 呼叫 hello-world 函數
const { data, error } = await supabase.functions.invoke('hello-world', {
body: { name: 'World' },
});
if (error) {
console.error('Error:', error);
} else {
console.log('Response:', data);
}
在開發和維護 Edge Functions 時,如何正確查看錯誤資訊:
這個技巧在除錯 API 呼叫、驗證授權 token 或檢查請求格式時非常有用。
# 查看本地函數日誌
supabase functions serve --debug
Supabase Dashboard 日誌查看:
除錯技巧:
console.log()
在函數中輸出除錯資訊// supabase/functions/hello-world/index.ts
Deno.serve(async req => {
const headersObject = Object.fromEntries(req.headers);
const headersJson = JSON.stringify(headersObject, null, 2);
console.log(`Request headers:\n${headersJson}`);
try {
const { name } = await req.json();
// 記錄處理訊息
console.log(`Processing request for: ${name}`);
const data = {
message: `Hello ${name || 'World'}!`,
};
return new Response(JSON.stringify(data), {
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
// 記錄錯誤訊息
console.error(`Request processing failed: ${error.message}`);
return new Response(JSON.stringify({ error: 'Internal Server Error' }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
});
}
});
當你不再需要某個函數時,需要完整清理相關檔案和配置:
# 方法一:使用 CLI 刪除
supabase functions delete hello-world
# 方法二:手動刪除
# 1. 刪除函數資料夾
rm -rf supabase/functions/hello-world
# 2. 清理配置檔案(檢查 supabase/config.toml)
# 移除函數相關的配置項目
# 3. 重新啟動本地環境
supabase stop
supabase start
提醒:
supabase functions delete
指令,它會自動處理相關清理工作後續會使用 Edge Functions 建立更複雜的應用場景,像是整合 Resend 信件發送、第三方 API 整合等。
... to be continued
有任何想討論歡迎留言,或需要指正的地方請鞭大力一點,歡迎訂閱、按讚加分享,分享給想要提升開發效率的朋友~