Having trouble accessing database from edge funtion. #32437
-
Hi. I'm trying to implement API token caching using a database table. I'm doing this by trying to fetch a token from a table then checking if it's expired, if it's not I'll just use the token i saved, otherwise I'll call the API I'm using to fetch a new token, then UPSERT it to the database. I'm trying to use the client library in the edge function by importing it with For some reason in the logs for the the edge function in docker i keep getting the following error
This is when trying to fetch the token from the database. I also get a similar error for trying to UPSERT a new token:
Doing a curl request for the data form the table with the service role key does actually show me the token row from the table so that rules out the table not being there and the RLS not being set up correctly. I've tried not using the client library and just writing our a fetch request myself but this seems to again give me similar It's part of the public schema This is the code I'm using for SELECT: const { data: token, error: selectError } = await supabase
.from("token_cache")
.select("token, created_at")
.eq("token_name", "osu_api_token")
.single();
if (selectError) {
console.error(
`Error fetching token from database: ${selectError.message}`,
);
} And this is the UPSERT: const newToken = await fetchToken();
if (newToken === null) {
return null;
}
console.log(newToken);
//Upsert the new token
const { error: upsertError } = await supabase
.from("token_cache")
.upsert({
token_name: "osu_api_token",
token: newToken,
});
if (upsertError) {
console.error(`Upsert error: ${upsertError.message}`);
return null;
} The This is the front end code i'm using to call the edge function itself: export async function recentPlays(userID) {
const url = "http://127.0.0.1:54321/functions/v1/osu-api";
const headers = {
"Content-Type": "application/json",
};
let response;
try {
response = await fetch(url, {
method: "POST",
headers,
body: JSON.stringify({ userID }),
});
if (!response.ok) {
console.log(
`HTTP error: ${response.status} - ${response.statusText}. In main call`,
);
}
const data = await response.json();
return data;
} catch (error) {
console.error("some wacky error:", error);
}
}
(async () => {
const plays = await recentPlays("22613198");
if (plays) {
console.log(plays);
}
})(); I've left out details about what the API is I'm trying to call I don't think this is important and this problem simply seems to be related to connecting to the supabase database API from the edge function environment. Just for completeness' sake here is the code i tried to use to interact with the database without using the client library: const tableName = "token_cahe";
const params = new URLSearchParams({ token_name: "osu_api_token" });
const url = `${supabaseUrl}/rest/v1/${tableName}?${params}`;
console.log(url);
const response = await fetch(url, {
headers: {
apikey: serviceKey,
Authorization: `Bearer ${serviceKey}`,
Accept: "application/vdn.pgrst.object+json",
},
});
if (!response.ok) {
console.error("api be bugging");
}
const { token, expires_in } = await response.json();
console.log(token, expires_in); I'm very new to webdev and supabase so this might be riddled with mistakes so I'm sorry if I'm making glaringly obvious and annoying mistakes, GPT can only carry me so far. Some other details that might be important is that I'm using parcel to bundle my front end and host a local server for the web page. I have made sure to implement the preflight check. Here is the entry point of the edge function: import { corsHeaders } from "../_shared/cors.ts";
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import { recentPlays } from "./recentPlays.ts";
import { getToken } from "./tokenFetch.ts";
Deno.serve(async (req: Request) => {
//CORS Preflight
if (req.method === "OPTIONS") {
console.log("Preflight...");
console.log(corsHeaders);
return new Response("ok", {
headers: { ...corsHeaders },
});
}
const { userID } = await req.json();
const token = await getToken();
if (token === null) {
return new Response("Failed to fetch token", {
headers: { ...corsHeaders },
status: 500,
});
}
const plays = await recentPlays(userID, token);
if (token === null) {
return new Response("Failed to fetch plays", {
headers: { ...corsHeaders },
status: 500,
});
}
return new Response(JSON.stringify(plays), {
headers: {
...corsHeaders,
"Content-Type": "application/json",
},
status: 200,
});
}); Cors headers: export const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers":
"authorization, x-client-info, apikey, content-type",
}; |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Please show how you are instantiating the Supabase client. The issue could be at that point in the code. |
Beta Was this translation helpful? Give feedback.
This is the issue, you cannot set these manually as the edge runtime is inside a docker container. You need to use the preset env variables that Supabase resolves automatically by itself.
You can read more about the default secrets here https://supabase.com/docs/guides/functions/secrets#default-secrets