Use edge functions in AnalyticDB Supabase

更新时间:
复制 MD 格式

AnalyticDB for PostgreSQL Supabase Edge Functions is a fully managed edge computing service that lets you deploy TypeScript Deno functions to your AnalyticDB Supabase projects. Compared with the open-source self-hosted Supabase, AnalyticDB Supabase provides complete Edge Functions management capabilities, giving you full control over your code and data with a development experience consistent with Supabase Cloud.

Overview

AnalyticDB Supabase Edge Functions provides a Deno-based edge computing solution that offers a modern serverless experience for full-stack application developers.

The open-source community version of Supabase does not include a function management backend, so self-hosted users cannot deploy to a production environment through a GUI or CLI. AnalyticDB Supabase fills this gap with its own Edge Functions management platform. All your code and configuration data reside in your private environment, making the feature production-ready.

AnalyticDB Supabase also provides centralized management of Edge Function secrets. You can store sensitive information, such as an Alibaba Cloud Model Studio API key, in a key vault and retrieve it using Deno.env.get, avoiding hardcoded credentials or client-side exposure.

Benefits

  • Native TypeScript development: No compilation or packaging is required. Deploy TypeScript source code directly.

  • Ecosystem integration: Directly access Supabase services such as the database, user authentication, and Object Storage Service from within a function without extra configuration.

  • Isolation and high performance: The sandbox mechanism and Deno security model ensure that each request runs independently, providing millisecond-level responses and nearly imperceptible cold starts.

Procedure

Deploy an edge function

Via dashboard

  1. Log on to the Supabase Dashboard.

  2. In the sidebar, click Edge Function > Functions.

  3. In the upper-right corner of the page, click Deploy a new function and select Via Editor from the drop-down list.

    image

  4. Write your code in the code editor.

    Important

    To import third-party dependencies or call public APIs in a function, you need to enable public network access for the AnalyticDB for PostgreSQL Supabase project.

    The following example includes index.ts (the entry file) and foo.ts.

    • The index.ts file is as follows:

      import { foo } from './foo.ts';
      console.info('server started');
      Deno.serve(async (req)=>{
        const { name } = await req.json();
        const data = {
          message: `Hello ${foo()} ${name}!`
        };
        return new Response(JSON.stringify(data), {
          headers: {
            'Content-Type': 'application/json',
            'Connection': 'keep-alive'
          }
        });
      });
    • The foo.ts file is as follows:

      export function foo() {
        return 'bar';
      }
  5. In the lower-right corner, enter a name for the Edge Function and click Deploy.

Via CLI

  1. Obtain and configure the SUPABASE_API_URL and SUPABASE_API_KEY for the target project.

    The SUPABASE_API_KEY is a service role key. For information about how to obtain the key, see Get API Keys. You can complete the configuration in one of the following ways:

    • Environment variable: export SUPABASE_API_KEY=xxx

    • .env file: SUPABASE_API_KEY=xxx

    • Command-line parameter: -key xxx

    The following example shows configuration using environment variables:

    export SUPABASE_API_URL=https://sbp-xxx.supabase.opentrust.net
    export SUPABASE_API_KEY=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoic2Vxxxx
  2. Prepare the function files.

    This example uses the following function directory structure, which includes index.ts (the entry file) and foo.ts.

    supabase
    └── functions
        └── hello
            ├── foo.ts
            └── index.ts
    • The index.ts file is as follows:

      import { foo } from './foo.ts';
      console.info('server started');
      Deno.serve(async (req)=>{
        const { name } = await req.json();
        const data = {
          message: `Hello ${foo()} ${name}!`
        };
        return new Response(JSON.stringify(data), {
          headers: {
            'Content-Type': 'application/json',
            'Connection': 'keep-alive'
          }
        });
      });
    • The foo.ts file is as follows:

      export function foo() {
        return 'bar';
      }
  3. Download the functions-cli tool. When you run the following commands, replace functions-cli with the name of the downloaded CLI tool.

  4. Deploy the function.

    Note
    • The deployment command searches for the supabase/functions/ path and a function directory named hello in the directory where you run the command.

    • If the "At least one file is required" error occurs, log on to the console. In the Actions column of the target Supabase project, choose More > Upgrade Version and then retry the operation. If your project version is v1.0.0, the database connection string is updated after the upgrade.

    ./functions-cli deploy hello

    To disable JWT verification when you deploy an Edge Function, add the --no-verify-jwt parameter. For example:

    ./functions-cli deploy hello --no-verify-jwt

Test an edge function

Via dashboard

  1. In the upper-right corner of the Functions page, click Test.

    image

  2. In the panel, click Send Request in the lower-right corner.

    image

Via curl command

On the Details tab, copy the curl command and replace [YOUR ANON KEY] with an anonymous key or a service role key.

image

Example output:

image

Update an edge function

  1. In the sidebar, click Edge Function > Functions, and then click the target function.

    image

  2. Click the Code tab and edit the target file.

  3. In the lower-right corner, click Deploy updates to update the Edge Function.

    image

Migrate an edge function

Migrate from Supabase Cloud

Step 1: Get project information

  1. Obtain a personal access token for the source project.

    1. Go to the Supabase Cloud console.

    2. On the Access Tokens page, click Generate new token.

      image

    3. Enter a token name and click Generate token.

      image

    4. Copy and securely store the token.

  2. Obtain the Project Ref for the source project.

    1. Go to the Supabase console.

    2. Click the source project and check the URL in your browser's address bar. The last part of the URL path is the Project Ref. For example, if the URL is https://supabase.com/dashboard/project/qeqfhfoebrtkbmwd****, the Project Ref is qeqfhfoebrtkbmwd****.

  3. Obtain the SUPABASE_API_URL and SUPABASE_API_KEY for the target project. The SUPABASE_API_KEY is the service role key. For more information, see Get API Keys.

  4. (Optional) Configure the project information. You can do so in one of the following ways:

    • Environment variable: export SUPABASE_API_KEY=xxx

    • .env file: SUPABASE_API_KEY=xxx

    • Command-line parameter: -key xxx

    The following example shows how to configure the information by using environment variables:

    export SUPABASE_SOURCE_REF=abcdefghijkl****
    export SUPABASE_SOURCE_TOKEN=sbp_1760f47cc82fe3466dce9aa*********
    
    export SUPABASE_API_URL=https://sbp-xxx.supabase.opentrust.net
    export SUPABASE_API_KEY=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoic2V****

Step 2: Install Deno

For more information, see Installation.

Step 3: Migrate using the CLI

  1. Download the functions-cli tool. When you run the following commands, replace functions-cli with the name of the downloaded CLI tool.

  2. Run the migration command.

    Single function

    Migrate a specific function by its slug:

    # Basic usage
    ./functions-cli migrate \
      -s hello \
      --source-ref abcdefghijkl**** \
      --source-token sbp_1a2b3c4d5e6f7g8h**** \
      --target-key eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoic2V**** \
      --target-url https://sbp-****.supabase.opentrust.net

    All functions

    ./functions-cli migrate \
      --all \
      --source-ref abcdefghijkl**** \
      --source-token sbp_1a2b3c4d5e6f7g8h**** \
      --target-key eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoic2V**** \
      --target-url https://sbp-****.supabase.opentrust.net

Sync between projects

Step 1: Get project information

  1. Obtain the SUPABASE_API_URL and SUPABASE_API_KEY for the source and target projects. The SUPABASE_API_KEY is the service role key. For more information, see Get API Keys.

  2. (Optional) Configure the project information. You can do so in one of the following ways:

    • Environment variable: export SUPABASE_API_KEY=xxx

    • .env file: SUPABASE_API_KEY=xxx

    • Command-line parameter: -key xxx

    The following example shows how to configure the information by using environment variables:

    export SOURCE_API_URL=https://sbp-source***.supabase.opentrust.net
    export SOURCE_API_KEY=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoic2V****
    
    export SUPABASE_API_URL=https://sbp-target***.supabase.opentrust.net
    export SUPABASE_API_KEY=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoic2V****

Step 2: Install Deno

For more information, see Installation.

Step 3: Sync using the CLI

  1. Download the functions-cli tool. When you run the following commands, replace functions-cli with the name of the downloaded CLI tool.

  2. Run the sync command.

    Single function

    Sync a specific function by its slug:

    ./functions-cli sync \
      -s hello \
      --source-key eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1Ni**** \
      --source-url https://sbp-source***.supabase.opentrust.net \
      --target-key eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1Ni**** \
      --target-url https://sbp-target***.supabase.opentrust.net

    All functions

    ./functions-cli sync \
      --all \
      --source-key eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.source_key_**** \
      --source-url https://sbp-source****.supabase.opentrust.net \
      --target-key eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.target_key_**** \
      --target-url https://sbp-target****.supabase.opentrust.net

Delete an edge function

  1. In the sidebar, click Edge Function > Functions, and then click the target function.

  2. Click the Details tab.

  3. In the Delete function section, click the Delete edge function button. In the confirmation dialog, click Delete.

    image

Secrets management

AnalyticDB Supabase provides centralized management of Edge Function secrets. You can store sensitive information in the key vault of the function's runtime environment and retrieve it using Deno.env.get, avoiding hardcoded credentials or client-side exposure.

Default secrets

Edge Functions can access the following secrets by default:

Parameter

Description

SUPABASE_URL

The API gateway URL of the AnalyticDB Supabase project.

SUPABASE_LOCAL_URL

The local API gateway URL for the AnalyticDB Supabase project. This URL bypasses the public network for lower latency.

SUPABASE_ANON_KEY

The anonymous key for the AnalyticDB Supabase API. When Row Level Security is enabled, this key is safe to use in a browser.

SUPABASE_SERVICE_ROLE_KEY

The service role key for the AnalyticDB Supabase API. This key is safe for use in Edge Functions but must never be exposed in a browser. This key bypasses Row Level Security restrictions.

Create custom secrets

Via dashboard

  1. In the sidebar, click Edge Function > Secrets.

  2. Enter the key and value.

    image

  3. Click save to add the secret.

Via CLI

  1. Download the functions-cli tool. When you run the following commands, replace functions-cli with the name of the downloaded CLI tool.

  2. Run the command to set the secrets.

    # Add a single secret
    functions-cli secrets set DASHSCOPE_API_KEY=sk_test123456
    
    # Add multiple secrets
    functions-cli secrets set DASHSCOPE_API_KEY=sk_test123456 OPENAI_API_KEY=test123456 
    
    # Add secrets from an .env file
    functions-cli secrets set --env-file supabase/functions/.env

Retrieve secrets in an edge function

Use Deno's built-in Deno.env.get() method to access environment variables by name. For a usage scenario, see Integrate with AI services.

Deno.env.get('NAME_OF_SECRET')