Logo

dev-resources.site

for different kinds of informations.

Supabase Edge Functions

Published at
11/24/2024
Categories
supabase
javascript
webdev
edgefunction
Author
hussain101
Author
10 person written this
hussain101
open
Supabase Edge Functions

Step-by-Step Guide to Using Edge Functions in Supabase and Scheduling Them with Cron Jobs
Edge Functions in Supabase allow you to deploy server-side logic that runs on the edge, enabling fast and scalable operations. Here’s how you can create and deploy edge functions and schedule them with cron jobs:

1- Install Supabase CLI:

Download and install the Supabase CLI. This will be used to manage your project and deploy edge functions.
Install via npm:
npm install -g supabase

Authenticate with Supabase:
supabase login

Initialize a Supabase Project Locally:

Navigate to your project directory in the terminal.
Run:
supabase init

2. Create an Edge Function
Generate a New Function:

Use the CLI to generate a new edge function:

supabase functions new my-function
Replace my-function with the name of your function.
Write Your Function Logic:

Navigate to the functions/my-function/index.ts file.
Add your logic, for example:
javascript
`import { serve } from 'https://deno.land/[email protected]/http/server.ts';

serve(async (req) => {
return new Response('Hello, world!', {
headers: { 'Content-Type': 'text/plain' },
});
});`
Test Locally:

Start the function locally:
supabase functions serve my-function
Access the function at http://localhost:54321/functions/v1/my-function.
Deploy the Function:

Deploy your function to Supabase:
supabase functions deploy my-function
For this you must have Docker installed, and it must be open!

  1. Test the Deployed Function Get the Function URL:

In the Supabase dashboard, navigate to Functions > my-function.
Copy the deployed function's URL.
Call the Function:

Use tools like curl, Postman, or JavaScript fetch to test the deployed function:
curl https://your-project-id.supabase.co/functions/v1/my-function

4. Schedule the Function with Cron Jobs
Install and Enable pg_cron in Supabase
Access Your Supabase Project:

Log in to your Supabase dashboard and open your project.
Enable pg_cron Extension:

Go to Database > Extensions.
Search for pg_cron and enable it by clicking the toggle.
Verify Installation:

Open the SQL Editor and run:
SELECT * FROM pg_available_extensions WHERE name = 'pg_cron';

Add a Postgres Function to Call the Edge Function
You need to create a PostgreSQL function that calls your Supabase Edge Function using HTTP.

Create the Postgres Function:

In the SQL Editor, write and execute:

`CREATE OR REPLACE FUNCTION call_edge_function()
RETURNS void AS $$
DECLARE
response jsonb;
BEGIN
-- Make an HTTP request to the Edge Function
SELECT INTO response
http_post(
'https://your-project-id.supabase.co/functions/v1/my-function', -- Replace with your Edge Function URL
'{}', -- Optional JSON payload (adjust as needed)
'Authorization=Bearer your-anon-key; Content-Type=application/json' -- Replace with your Supabase anon key
);

-- Optionally log the response (for debugging)
RAISE NOTICE 'Response: %', response;
END;
$$ LANGUAGE plpgsql;`
Replace:

your-project-id with your Supabase project ID.
your-anon-key with your Supabase anon key (available in the dashboard under Settings > API).
Test the Postgres Function:

Call the function manually to ensure it works:

SELECT call_edge_function();
Check the output for any errors.

  1. Schedule the Function with pg_cron Create a Cron Job:

In the SQL Editor, write and execute:

SELECT cron.schedule(
'call_edge_function_job', -- Unique name for the job
'0 * * * *', -- Cron expression (e.g., every hour)
$$ SELECT call_edge_function(); $$
);

Replace the cron expression with your desired schedule. For example:

Every minute: * * * * *
Every hour: 0 * * * *
Every day at midnight: 0 0 * * *
List Scheduled Jobs:

Verify the job was created:
SELECT * FROM cron.job;
Remove or Update a Cron Job:

To remove a job:

SELECT cron.unschedule('call_edge_function_job');
Enter fullscreen mode Exit fullscreen mode

By following these steps, you’ll have a fully functional edge function deployed on Supabase and scheduled with a cron job to run at your desired intervals.

supabase Article's
30 articles in total
Favicon
Building Production-Grade Web Applications with Supabase – Part 1
Favicon
Tracing and Metrics in supabase/storage
Favicon
Understanding Storage backends in supabase/storage
Favicon
Auth in Supabase storage
Favicon
Overview of supabase storage repository
Favicon
Harnessing the Power of Self-Hosted Supabase on Coolify: A Complete Guide to Server Setup and OAuth Providers Integration
Favicon
checa como se hace una conexión entre nextjs y la autenticación de supabase
Favicon
Deploying an Existing Express API + Prisma + Supabase Project to Vercel
Favicon
Custom schema specific Supabase Server Component clients in Grida Form workspace
Favicon
Custom schema specific Supabase Client Component clients in Grida Form workspace
Favicon
Introducing Supabase Client Playground: The Ultimate Tool for Streamlined Query Testing
Favicon
hCaptcha, a bot detection tool, usage in Supabase and Chatwoot
Favicon
Securing Client-Side Routes in Next.js with Supabase
Favicon
How to Transfer PostgreSQL Database from Local to Supabase on macOS
Favicon
Supabase | My Way of Designing & Managing DB
Favicon
What does Supabase use for its Authentication?
Favicon
É seguro guardar dados do usuário no localStorage?
Favicon
Supabase RLS Alternative
Favicon
Build Queue Worker using Supabase Cron, Queue and Edge Function
Favicon
Supabase Just Got More Powerful: Queue, Cron, and Background Tasks in Edge Functions
Favicon
Comparison of the middleware implementation between Supabase Auth documentation and the nextjs-stripe-supabase.
Favicon
How Supabase implemented micro-frontends using Multi Zones in Next.js
Favicon
Unlocking User Data: Building a Secure Supabase Edge Function
Favicon
Usecase: TumbleLog
Favicon
Supabase Edge Functions
Favicon
Setup Astro With Supabase and Prisma
Favicon
We launched SupaCharts! Visualize Beautiful Charts from your Supabase Data.
Favicon
A Free Minimalistic SaaS Starter Kit for Fast MVP Building
Favicon
supabase注册并创建项目和添加数据表
Favicon
Integrating GitHub Authentication with NextAuth.js: A Step-by-Step Guide

Featured ones: