Learn how to call an edge function from your Supabase frontend. Set up your project, deploy with CORS, and test using fetch in this step-by-step guide.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
Step 1: Set Up a Supabase Project
Step 2: Create an Edge Function in Supabase
In your Supabase dashboard, navigate to the "Edge Functions" tab.
Click on "New Function" to create a new Supabase Edge Function.
Define your function. For example, let's create a simple "Hello World" function:
export default (req, res) => {
res.json({ message: "Hello, World!" });
};
Step 3: Set Up CORS Headers
In order to call this function from the frontend, you need to ensure CORS (Cross-Origin Resource Sharing) is set up properly.
Update your function's code to include CORS headers like so:
export default (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '\*');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
if (req.method === 'OPTIONS') {
return res.status(200).send('OK');
}
res.json({ message: "Hello, World!" });
};
Step 4: Integrate with Frontend
In your frontend application, you'll need to make a call to this edge function using the fetch API or any HTTP request library like Axios.
Here's how you can do this with fetch:
const callEdgeFunction = async () => {
const response = await fetch('https://your-function-url.supabase.co/', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
});
const data = await response.json();
console.log(data.message);
};
callEdgeFunction();
'https://your-function-url.supabase.co/'
with the actual URL of your deployed function.
Step 5: Test the Integration
callEdgeFunction()
to verify that the response from the Edge function is displayed correctly in the console.
Step 6: Troubleshoot and Debug if Necessary
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.