Brady Dowling
Brady Dowling

Reputation: 5542

How to use JS client to pass formData to Supabase Edge function

I'm trying to call a Supabase edge function using the JS/TS client and pass audio from the client to the server. In doing this, I'm using formData on the client and trying to pass it in the body. Here's my client code:

  const formData = new FormData();
  
  const file = await fetch(uri);
  const fileBlob = await file.blob();
  const filename = getFileName(uri);
  formData.append("file", fileBlob, filename);

  const { data, error } = await supabase.functions.invoke("openai", {
    body: formData,
  });

On the server, I'm parsing the form data as follows:

// Supabase functions handler
serve(async (req) => {
  const form = await multiParser(req);

  if (form) {
    console.log("There is a form!");
    return new Response(JSON.stringify({}));
  }
  console.log("No form sent");
  return new Response(JSON.stringify({}));
});

And it's just logging "No form sent". Is there a way to send form data using the Supabase client? Or do I need to just make the request using fetch or axios? Or is there a better way to send audio from the browser to a Supabase/Deno function?

Upvotes: 0

Views: 1253

Answers (1)

Brady Dowling
Brady Dowling

Reputation: 5542

This issue in this case was that I wasn't handling the OPTIONS call that happened before the POST call. This needs to happen because it was being invoked from the browser (see here for CORS and supabase).

So I had to declare corsHeaders in a shared file:

export const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}

And then import it and add a conditional handler at the very beginning of the function:

import { corsHeaders } from "../_shared/cors.ts"

serve(async (req) => {
  if (req.method === "OPTIONS") {
    return new Response("ok", { headers: corsHeaders });
  }

  ...

Upvotes: 0

Related Questions