Supabase edge functions

Supabase edge functions

Introduction

Supabase is a cloud platform that lets developers create web and mobile apps without the need for servers. It's a cost-effective way to build and operate applications that can flexibly scale, and edge functions offer an easy way to add serverless functions.

What are Supabase edge functions?

Edge functions in Supabase let you build feature-rich applications, connect them to databases, and process data in real time. The JavaScript runtime, Deno, is used to execute the functions. With edge functions, you can serve content from the nearest CDN server to a user as well as modify network requests at the edge without manual intervention, something possible with Deno Deploy (a distributed system that permits JavaScript, TypeScript, and WebAssembly to be executed closest to users). You can focus on developing your logic while Supabase takes care of the underlying technologies.

The Edge function receives incoming requests at its Relay, which serves as an API access gateway and authenticates JWTs in headers along with logging and rate-limiting features. When a function request is received, Relay collects data about the function as well as its deployment ID and then sends it over to Deno; which executes the function code before sending the response back to the user.

But how do you write Edge functions? What's the optimal way to write serverless code? How do you deploy edge functions? All these answers will be given in this article!

Getting Started

To get started with Supabase Edge functions, you’ll need the following installed. Install the Supabase CLI:

npm install -g supabase --save-dev

Log into CLI by entering:

npx supabse login

Initialize your project by entering:

npx supabse login

Link your local project to a remote Supabase project by entering: (here is a tutorial on how to create a remote Supabase project.) Supabase

supabase link --project-ref

Real-world scenario chat app with Twilio

Your first edge functions

You will create a message Edge function that will send SMS using Twilio's messaging API.

To create edge functions with Supabase, run the below command, where message is your function name.

 supabase functions new message

This creates a boilerplate of code inside your Supabase folder: ./functions/message/index.ts

Create a .env file at the root of the project and add the following values to your file.

TWILIO_ACCOUNT_SID='Account SID' 
TWILIO_AUTH_TOKEN='Auth Token'
TWILIO_PHONE_NUMBER='My Twilio phone number'

Replace the values with env variables copied from your Twilio account console

Define your interface to represent the message payload ./message/types/interface.ts

export interface Sms {
    [index: string]: string;
    From: string;
    To: string;
    Body: string;
  }

Next, you need to create a helper class to send SMS. The class constructor will take the account SSID and Auth Token which are encoded together and passed as authorization header in the API Request. ../message/helpers/message-helper.ts

import * as base64 from "https://denopkg.com/chiefbiiko/base64/mod.ts";
import { Sms } from "../types/interface.ts";

export class TwilioSms {
  private authorizationHeader: string;

  constructor(private accountSID: string, authToken: string) {
    this.authorizationHeader =
      "Basic " +
      base64.fromUint8Array(
        new TextEncoder().encode(accountSID + ":" + authToken)
      );
  }
  async sendSms(payload: Sms): Promise<any> {
    const res = await fetch(
      "https://api.twilio.com/2010-04-01/Accounts/" +
        this.accountSID +
        "/Messages.json",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
          Authorization: this.authorizationHeader,
        },
        body: new URLSearchParams(payload).toString(),
      }
    );
    const data = await res.json();
    return data;
  }
}

Next, create a send message and use the sendsms() method to send the message to the specified number in the request body respectively. add the following code to your ./message/index.ts

import { serve } from "https://deno.land/std@0.131.0/http/server.ts";
import { TwilioSms } from "./helpers/twilio-sms.ts";
const accountSid = Deno.env.get("TWILIO_ACCOUNT_SID") || "";
const authToken = Deno.env.get("TWILIO_AUTH_TOKEN") || "";
const fromMobile = Deno.env.get("TWILIO_PHONE_NUMBER") || "";

serve(async (req) => {
      const { textMessage, toMobile } = await req.json();
      const twilioClient = new TwilioSms(accountSid, authToken);
      const message = await twilioClient.sendSms({
        Body: textMessage,
        From: fromMobile,
        To: toMobile,
      });
      const data = {
        isSuccess: false,
      };

      if (message.status === "queued") {
        data.isSuccess = true;
      }

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

Deploy edge functions with supabase

To deploy your message edge functions run the following command

 supabase deploy functions message

The function packages your functional code and deploys it to a remote Supabase project. Below, in your supabase dashboard, click on the URL to invoke. Copy and paste the curl request to test your functions from the terminal below

the dashboard image

curl -L -X POST 'https://rmaqhwfotslevjnyljav.functions.supabase.co/message' -H 'Authorization: Bearer [YOUR ANON KEY]' --data '{"name":"Functions"}

Run locally

To run the Supabase Edge function locally, you need to have the Subabase Studio installed locally. Check out the official documents here on how to get started. To start your Supabase project run

supabase start

Next, you need to start the message function

npx supabase functions serve message

This command will startlocal server listeningport 54321 for the message function. Make a curlrequest from your command line to invoke your function.

curl --request POST 'http://localhost:54321/functions/v1/message' --header 'Authorization: Bearer [YOUR ANON KEY]' --header 'Content-Type: application/json' --{"name":"Functions"}

The Bearer token in the header for authentication can be your project’s anon key, or SERVICE_ROLE key or user’s JWT token

Conclusion

We've gone over how Supabase Edge Functions can benefit users, making their experience much better. With the recent growth of serverless computing, developers can use this powerful tool to enhance their projects and really wow their users.