Supabase Functions are incredibly powerful because they can directly interact with your Supabase database. This means you can write server-side logic that reads, writes, updates, and deletes data just as if you were writing a regular server application, but without the hassle of managing your own server infrastructure. This section will guide you through the essentials of database interaction within your Supabase Functions.
The magic happens through the Supabase JavaScript client. When you create a Supabase Function (typically written in JavaScript or TypeScript), you have access to a pre-initialized Supabase client instance. This client is already configured with your project's URL and anon key, allowing you to authenticate and interact with your database seamlessly.
import { serve } from "https://deno.land/std@0.177.0/http/server.ts";
import {
createClient
} from "https://esm.sh/@supabase/supabase-js";
const supabaseUrl = Deno.env.get("SUPABASE_URL");
const supabaseAnonKey = Deno.env.get("SUPABASE_ANON_KEY");
// Initialize the Supabase client within the function
const supabase = createClient(supabaseUrl, supabaseAnonKey);
console.log("Supabase client initialized!");
serve(async (req) => {
// Your database interaction logic will go here
return new Response(JSON.stringify({ message: "Function started" }), {
headers: { "Content-Type": "application/json" },
});
});Let's explore some common database operations you can perform.
Fetching data is straightforward. You'll use the .from() method to specify your table, followed by methods like .select() to define which columns you want and .eq() or .in() for filtering. The .single() modifier is useful when you expect only one row.
const { data, error } = await supabase
.from('todos')
.select('*')
.eq('user_id', 'some-user-id');
if (error) {
console.error('Error fetching todos:', error);
// Handle the error appropriately
}
console.log('Fetched todos:', data);