What if you could securely fetch live data for your users without slowing down your site or risking secrets?
Why Calling external APIs from Edge Functions in Supabase? - Purpose & Use Cases
Imagine you have a website that needs to get fresh weather data from another service every time someone visits. You try to do this by asking the visitor's browser to fetch the data directly from that weather service.
But what if the visitor's browser blocks the request? Or the weather service requires a secret key you don't want to share with everyone?
Doing this manually means you rely on each visitor's browser to talk to the external service. This can be slow, unreliable, and risky because you might expose secret keys or face security blocks like CORS errors.
Also, if you try to handle this on your main server, it can slow down your site and make it harder to scale.
Edge Functions let you run small pieces of code close to your users, acting as a secure middleman. They can safely call external APIs with secret keys, process the data, and send back only what your site needs.
This makes your site faster, safer, and more reliable without exposing secrets or waiting for slow servers.
fetch('https://weatherapi.com/data?city=NYC')
.then(res => res.json())
.then(data => console.log(data))export default async function handler(req) {
const res = await fetch('https://weatherapi.com/data?city=NYC', {
headers: { 'Authorization': 'Bearer SECRET_KEY' }
})
const data = await res.json()
return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } })
}Edge Functions unlock the power to securely and quickly connect your app to any external service right at the network edge.
A shopping site uses Edge Functions to get live stock updates from suppliers without exposing API keys or slowing down the user experience.
Manual API calls from browsers can be blocked or insecure.
Edge Functions run close to users and keep secrets safe.
This makes your app faster, safer, and more reliable.
Practice
fetch in Supabase Edge Functions when calling external APIs?Solution
Step 1: Understand the role of
fetchin Edge Functionsfetchis used to send HTTP requests to external APIs and get responses back.Step 2: Identify what
It does not store data permanently or create UI components; it only communicates with external services.fetchdoes not doFinal Answer:
To send requests and receive data from external services -> Option DQuick Check:
fetch calls external APIs = C [OK]
- Thinking fetch stores data permanently
- Confusing fetch with database queries
- Assuming fetch creates UI elements
fetch inside a Supabase Edge Function?Solution
Step 1: Recall the correct usage of fetch
fetch returns a promise; to get JSON data, you callthen(res => res.json()).Step 2: Check each option for syntax correctness
const response = fetch('https://api.example.com/data') misses handling the promise; B uses invalid method; D incorrectly callsjson()directly on fetch.Final Answer:
const response = fetch('https://api.example.com/data').then(res => res.json()) -> Option AQuick Check:
fetch + then(res.json()) = A [OK]
- Calling json() directly on fetch without then or await
- Using fetch.get which does not exist
- Ignoring the promise returned by fetch
export async function handler() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return new Response(JSON.stringify({ result: data.value }), { status: 200 });
}
If the external API returns { "value": 42 }, what will the Edge Function return?Solution
Step 1: Understand the API response and parsing
The API returns JSON {"value": 42}, which is parsed into data object with data.value = 42.Step 2: Check the returned response from the Edge Function
The function returns JSON string with key "result" and value data.value (42), status 200.Final Answer:
A response with body '{"result":42}' and status 200 -> Option BQuick Check:
API value 42 mapped to result key = D [OK]
- Returning original API JSON without mapping
- Confusing status codes
- Assuming data.value is undefined
export async function handler() {
const response = fetch('https://api.example.com/data');
const data = await response.json();
return new Response(JSON.stringify(data), { status: 200 });
}
What is the main error in this code?Solution
Step 1: Identify how fetch is called
fetch returns a Promise, so it must be awaited to get the response object.Step 2: Check usage of await on response.json()
Awaiting response.json() is correct; the error is missing await on fetch.Final Answer:
Missing await before fetch causing response to be a Promise -> Option AQuick Check:
Missing await before fetch causing response to be a Promise = B [OK]
- Not awaiting fetch before response.json()
- Thinking response.json() does not need await
- Misunderstanding Response constructor usage
Solution
Step 1: Understand sequential API calls
To call APIs one after another, await each fetch and parse before next call.Step 2: Check each option for correct async handling
const res1 = await fetch('https://api1.com/data'); const data1 = await res1.json(); const res2 = await fetch('https://api2.com/data'); const data2 = await res2.json(); return new Response(JSON.stringify({ first: data1, second: data2 }), { status: 200 }); correctly awaits each fetch and json parsing sequentially. const res1 = fetch('https://api1.com/data'); const data1 = await res1.json(); const res2 = fetch('https://api2.com/data'); const data2 = await res2.json(); return new Response(JSON.stringify({ first: data1, second: data2 }), { status: 200 }); misses await on fetch. const [res1, res2] = await Promise.all([ fetch('https://api1.com/data'), fetch('https://api2.com/data') ]); const data1 = await res1.json(); const data2 = await res2.json(); return new Response(JSON.stringify({ first: data1, second: data2 }), { status: 200 }); uses parallel calls, not sequential. const data1 = fetch('https://api1.com/data').json(); const data2 = fetch('https://api2.com/data').json(); return new Response(JSON.stringify({ first: data1, second: data2 }), { status: 200 }); incorrectly calls json() directly.Final Answer:
const res1 = await fetch('https://api1.com/data');\nconst data1 = await res1.json();\nconst res2 = await fetch('https://api2.com/data');\nconst data2 = await res2.json();\nreturn new Response(JSON.stringify({ first: data1, second: data2 }), { status: 200 }); -> Option CQuick Check:
Sequential await fetch + json = A [OK]
- Not awaiting fetch before json()
- Calling json() directly on fetch
- Mixing parallel and sequential calls incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
