Develop Supabase Backend Service
Learn how to develop Supabase backend service in the EasyAppSupabase project
Local Development Environment Setup
Start Local Supabase Service
Run in the EasyAppSupabase directory:
cd EasyAppSupabase
npx supabase startBefore downloading Docker images, we recommend installing Docker Desktop
The first run will download Docker images, which may take a few minutes.
Check Service Status
npx supabase status
This will display URLs and keys for all services, including:
- API URL:
http://localhost:54321 - Database URL:
postgresql://postgres:[PASSWORD]@localhost:54322/postgres - Secret key: For client requests
Then add the API URL and Secret key to the EasyAppSwiftUI/Constants/Constants.swift file.
enum Supabase {
/// Development supabase url
#if DEBUG
static let url = "http://localhost:54321"
/// The anon key
static let key ="your_anon_key_here"
#else
}Developing Edge Functions
The SupabaseEdgeFunction project already has built-in all the Edge Functions required for the easyapp template. You can refer to these functions to create your own functions.
Generate Function Using CLI
npx supabase functions new my-functionThis creates a basic template in the supabase/functions/my-function/ directory:
// supabase/functions/my-function/index.ts
import "jsr:@supabase/functions-js/edge-runtime.d.ts"
Deno.serve(async (req) => {
const { name } = await req.json()
const data = {
message: `Hello ${name}!`,
}
return new Response(
JSON.stringify(data),
{ headers: { "Content-Type": "application/json" } },
)
})Configure Dependencies
Create a deno.json file to manage dependencies:
{
"imports": {
"@supabase/supabase-js": "jsr:@supabase/supabase-js@^2.50.2",
"@openai/openai": "jsr:@openai/openai@^5.8.1"
}
}Access Environment Variables
In your function, you can access environment variables through Deno.env.get():
// Get environment variables
const apiKey = Deno.env.get("OPENAI_API_KEY")
const customVar = Deno.env.get("YOUR_CUSTOM_VARIABLE")Using Shared Tools
EasyAppSupabase provides pre-configured shared tools that can be used directly in your functions:
Using Supabase Client
import {
supabaseServiceRoleKey,
supabaseUrl,
} from "../_shared/SupabaseClient.ts";
import { createClient } from "@supabase/supabase-js";
Deno.serve(async (req) => {
const supabaseClient = createClient(
supabaseUrl,
supabaseServiceRoleKey,
);
// Get user authentication info
const authHeader = req.headers.get("Authorization");
if (!authHeader) {
return new Response("Unauthorized", { status: 401 });
}
const token = authHeader.replace("Bearer ", "");
const { data: user } = await supabaseClient.auth.getUser(token);
if (!user) {
return new Response("Invalid token", { status: 401 });
}
// Database operations
const { data, error } = await supabaseClient
.from('your_table')
.select('*')
.eq('user_id', user.user.id);
return new Response(JSON.stringify(data), {
headers: { "Content-Type": "application/json" }
});
});Using OpenAI Client
import { openAIClient } from "../_shared/OpenAIClient.ts";
import { createClient } from "@supabase/supabase-js";
Deno.serve(async (req) => {
const { prompt } = await req.json();
const response = await openAIClient.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: prompt }],
});
return new Response(JSON.stringify({
result: response.choices[0].message.content
}), {
headers: { "Content-Type": "application/json" }
});
});Local Testing
Configure Environment Variables
Configure your environment variables in the supabase/.env.local file:
# supabase/.env.local
# OpenAI
OPENAI_API_KEY=your_openai_api_key_here
# Supabase
# supabase local development uses LOCAL_DEV prefix
LOCAL_DEV_SUPABASE_URL=http://127.0.0.1:54321
LOCAL_DEV_SUPABASE_SERVICE_ROLE_KEY=your_supabase_service_role_key_here
# Other environment variablesLOCAL_DEV_SUPABASE_SERVICE_ROLE_KEY can be obtained from here

Configure Database Tables
- Create a new migration file:
npx supabase migration new your_migration_name-
Edit the generated SQL file in
supabase/migrations/ -
Apply migration:
npx supabase db pushStart Function Service
# Start specific function and load environment variables
npx supabase functions serve my-function --env-file ./supabase/.env.local
# Start all functions and load environment variables
npx supabase functions serve --env-file ./supabase/.env.localThe function will run at http://localhost:54321/functions/v1/my-function.
Test Function
Use curl to test your function:
# Get local anon key
npx supabase status
# Test function
curl -i --location --request POST 'http://localhost:54321/functions/v1/my-function' \
--header 'Authorization: Bearer YOUR_LOCAL_ANON_KEY' \
--header 'Content-Type: application/json' \
--data '{"name":"World"}'View Logs
Function logs will display in real-time in the terminal to help you debug issues.
Best Practices
Security
- Always verify user identity (unless it's a public Webhook)
- Use environment variables to store sensitive information (API keys, database connection strings, etc.)
- Implement proper error handling
Troubleshooting
Common Issues
Function won't start
- Make sure Docker is running
- Run
supabase stopthensupabase startto restart services
Port conflicts
- Check
supabase statusto see occupied ports - Stop other Supabase instances
Deployment fails
- Check function code syntax
- Ensure all dependencies are properly configured
- Verify environment variable settings
Environment variables can't be read
- Ensure
.env.localfile format is correct (KEY=value) - Use
--env-fileparameter when starting functions - Check if environment variable names are spelled correctly
View Logs
# View function logs
npx supabase functions logs my-function
# View logs in real-time
npx supabase functions logs my-function --followThrough this guide, you should be able to successfully create, test, and deploy Supabase Cloud Functions in your EasyAppSupabase project.
To learn more about Supabase Cloud Functions, please refer to the official Supabase Cloud Functions documentation
Last updated on