开始使用 Edge 函数
Learn how to create, test, and deploy your first Edge Function using the Supabase CLI.
本指南将带你了解如何使用 CLI 创建、在本地测试、部署和调用 Supabase Edge 函数。到最后,你就能在 Supabase 的全球边缘网络上运行一个可用的函数了。
🌐 This guide walks you through creating, testing locally, deploying, and invoking a Supabase Edge Function using the CLI. By the end, you'll have a working function running on Supabase's global edge network.
你也可以直接在 Supabase 仪表板上创建和部署函数。想了解更多信息,请阅读仪表板快速入门指南。
🌐 You can also create and deploy functions directly from the Supabase Dashboard. Read the Dashboard Quickstart guide for more information.
Supabase Edge Functions 只支持使用 Deno 运行时 用 TypeScript 创建函数。这是因为 Deno 在设计时就考虑了可扩展性,它的 Rust 代码库提供了现代开发者体验、内存安全以及其他非常适合运行边缘函数的功能。
🌐 Supabase Edge Functions only supports creating functions in TypeScript with the Deno runtime. This is because Deno was designed with extensibility in mind and its Rust codebase offers a modern developer experience, memory safety, and other features ideal for running edge functions.
先决条件 #
🌐 Prerequisites
- 确保你已经安装并配置好了 Supabase CLI。查看CLI 安装指南了解安装方法和故障排除。
- 在本地运行和测试 Supabase Edge Functions 需要 Docker 或兼容 Docker 的运行时。
步骤 1:创建或配置你的项目 #
🌐 Step 1: Create or configure your project
如果你还没有项目,可以在当前目录下初始化一个新的 Supabase 项目。
🌐 If you don't have a project yet, initialize a new Supabase project in your current directory.
1mkdir my-edge-functions-project2cd my-edge-functions-project3supabase init如果你已经在本地有一个项目,先进入你的项目目录。如果你还没有为 Supabase 配置项目,记得运行 supabase init 命令。
🌐 If you already have a project locally, navigate to your project directory. If you haven't configured the project for Supabase yet, make sure to run the supabase init command.
1cd your-existing-project2supabase init # Initialize Supabase, if you haven't already完成这一步后,你应该有一个项目目录,其中 supabase 文件夹包含一个 config.toml 文件。
🌐 After this step, you should have a project directory with a supabase folder containing a config.toml file.
第2步:创建你的第一个函数 #
🌐 Step 2: Create your first function
在你的项目中,用一个基本模板生成一个新的 Edge Function:
🌐 Within your project, generate a new Edge Function with a basic template:
1supabase functions new hello-world用 Supabase 认证保护你的功能
当向 Edge Functions 发送 HTTP 请求时,你可以使用 Supabase Auth 来保护端点。默认情况下,supabase functions new 命令会在基本模板中加入处理有效的可发布密钥或秘密密钥的功能。不过,在创建新函数时,你可以使用 --auth 标志来更改这个行为。
🌐 When an HTTP request is sent to Edge Functions, you can use Supabase Auth to secure endpoints. By default, the supabase functions new command adds handling a valid publishable or secret key to the basic template. However, you can change this behavior with the --auth flag when creating a new function.
这会在 supabase/functions/hello-world/index.ts 创建一个带有以下起始代码的新函数:
🌐 This creates a new function at supabase/functions/hello-world/index.ts with this starter code:
1export default {2 fetch: withSupabase({ auth: ['publishable', 'secret'] }, async (req, ctx) => {3 const { name } = await req.json()45 return Response.json({6 message: `Hello ${name}!`,7 })8 }),9}这个函数接受一个包含 name 字段的 JSON 数据,并返回一个问候消息。
🌐 This function accepts a JSON payload with a name field and returns a greeting message.
supabase functions new 命令还可以选择性地为 VSCode 创建 Deno 配置。
🌐 The supabase functions new command also optionally creates Deno configuration for VSCode.
第3步:在本地测试你的函数 #
🌐 Step 3: Test your function locally
启动 Docker 后,启动本地开发服务器来测试你的功能:
🌐 After starting Docker, start the local development server to test your function:
1supabase start # Start all Supabase services2supabase functions serve hello-world第一次使用时,supabase start 命令会下载 Docker 镜像,并在本地启动所有 Supabase 服务,这可能需要几分钟时间。
🌐 On first use, the supabase start command downloads Docker images, and starts all Supabase services locally, which can take a few minutes.
你的函数现在正在 http://localhost:54321/functions/v1/hello-world 运行。热重载已启用,这意味着当你保存函数代码的更改时,服务器会自动重新加载。保持这个终端窗口打开。
🌐 Your function is now running at http://localhost:54321/functions/v1/hello-world. Hot reloading is enabled, which means that the server automatically reloads when you save changes to your function code. Keep this terminal window open.
功能在本地无法启动吗? #
🌐 Function not starting locally?
- 确保 Docker 正在运行
- 先运行
supabase stop,然后运行supabase start来重启服务
端口已经被占用了? #
🌐 Port already in use?
- 用
supabase status查看正在运行的内容 - 用
supabase stop停止其他 Supabase 实例
第4步:发送测试请求 #
🌐 Step 4: Send a test request
打开一个新的终端,并用 curl 测试你的函数。你可以通过运行 supabase status 来找到你的本地可发布密钥,或者你也可以在 functions/hello-world/index.ts 中找到完整的 curl 命令。
🌐 Open a new terminal and test your function with curl. You can find your local Publishable key, by running supabase status, or you can find the complete curl command already in functions/hello-world/index.ts.
1curl -i --location --request POST 'http://127.0.0.1:54321/functions/v1/hello-world' \2 --header 'apiKey: <SUPABASE_PUBLISHABLE_KEY>' \3 --data '{"name":"Functions"}'运行这个 curl 命令后,你应该会看到:
🌐 After running this curl command, you should see:
1{ "message": "Hello Functions!" }你也可以尝试不同的输入。在 curl 命令中把 "Functions" 改成 "World",然后再运行一次看看响应变化。
🌐 You can also try different inputs. Change "Functions" to "World" in the curl command and run it again to see the response change.
完成这一步后,你应该已经成功在本地测试了你的 Edge 函数,并收到了包含问候信息的 JSON 响应。
🌐 After this step, you should have successfully tested your Edge Function locally and received a JSON response with your greeting message.
步骤5:连接到你的Supabase项目 #
🌐 Step 5: Connect to your Supabase project
要把你的函数部署到全球,你需要把本地项目连接到 Supabase 项目。
🌐 To deploy your function globally, you need to connect your local project to a Supabase project.
需要创建一个新的 Supabase 项目吗?
在 database.new 创建一个。
🌐 Create one at database.new.
首先,如果你还没登录 CLI,请先登录,并用 Supabase 进行认证。这会打开你的浏览器以使用 Supabase 进行认证;在浏览器中完成登录过程。
🌐 First, login to the CLI if you haven't already, and authenticate with Supabase. This opens your browser to authenticate with Supabase; complete the login process in your browser.
1supabase login接下来,列出你的 Supabase 项目来找到你的项目 ID:
🌐 Next, list your Supabase projects to find your project ID:
1supabase projects list接下来,从输出中复制你的项目 ID,然后将你的本地项目连接到远程 Supabase 项目。用上一步的 ID 替换 YOUR_PROJECT_ID。
🌐 Next, copy your project ID from the output, then connect your local project to your remote Supabase project. Replace YOUR_PROJECT_ID with the ID from the previous step.
1supabase link --project-ref [YOUR_PROJECT_ID]完成这一步后,你的本地项目应该已经通过认证并链接到远程的 Supabase 项目。你可以通过运行 supabase status 来验证这一点。
🌐 After this step, you should have your local project authenticated and linked to your remote Supabase project. You can verify this by running supabase status.
第6步:部署到生产环境 #
🌐 Step 6: Deploy to production
将你的函数部署到 Supabase 的全球边缘网络:
🌐 Deploy your function to Supabase's global edge network:
1supabase functions deploy hello-world如果你想部署所有功能,请运行 deploy 命令而不指定功能名称:
🌐 If you want to deploy all functions, run the deploy command without specifying a function name:
1supabase functions deploy不需要 Docker
如果 Docker 不可用,CLI 会自动回退到基于 API 的部署。你也可以用 --use-api 标志显式使用 API 部署:
🌐 The CLI automatically falls back to API-based deployment if Docker isn't available. You can also explicitly use API deployment with the --use-api flag:
1supabase functions deploy hello-world --use-api当部署成功后,你的函数会自动分发到全球的边缘节点。
🌐 When the deployment is successful, your function is automatically distributed to edge locations worldwide.
现在,你的 Edge 功能应该已经部署好了,并且在全球范围内运行在 https://[YOUR_PROJECT_ID].supabase.co/functions/v1/hello-world。
🌐 Now, you should have your Edge Function deployed and running globally at https://[YOUR_PROJECT_ID].supabase.co/functions/v1/hello-world.
第7步:测试你的实时功能 #
🌐 Step 7: Test your live function
🎉 你的功能现在已上线!用你项目的可发布密钥测试它,你可以在 仪表板 的 设置 > API 密钥 部分找到该密钥:
1curl --request POST 'https://[YOUR_PROJECT_ID].supabase.co/functions/v1/hello-world' \2 --header 'apikey: <SUPABASE_PUBLISHABLE_KEY>' \3 --header 'Content-Type: application/json' \4 --data '{"name":"Production"}'预期回应:
1{ "message": "Hello Production!" }用法 #
🌐 Usage
现在你的函数已经部署好了,你可以在应用中调用它了:
🌐 Now that your function is deployed, you can invoke it from within an app:
1import { createClient } from '@supabase/supabase-js'23const supabase = createClient('https://[YOUR_PROJECT_ID].supabase.co', 'YOUR_PUBLISHABLE_KEY')45const { data, error } = await supabase.functions.invoke('hello-world', {6 body: { name: 'JavaScript' },7})89console.log(data) // { message: "Hello JavaScript!" }