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 '.
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!
- 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 ', -- 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.
- 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');
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.
SOCIAL SHARE CARD GENERATOR