Search code examples
javascriptsveltekitsupabasedenoedge-function

Error when trying to call a supabase edge function


I am trying to call a supabase edge function in javascript but I am getting this error:

access to fetch at 'https:/blablala.functions.supabase.co/hello-world' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

This is how the function looks like (default when creating the function):

import { serve } from "https://deno.land/[email protected]/http/server.ts";

console.log("Hello from Functions!");

serve(async (req) => {
  const { name } = await req.json();
  const data = {
    message: `Hello ${name}!`,
  };

  return new Response(JSON.stringify(data), {
    headers: { "Content-Type": "application/json" },
  });
});

and this is how it looks when I try to call it (just like the docs):

import { supabase } from "$lib/supabaseClient";

  const functionTest = async () => {
    const { data, error } = await supabase.functions.invoke("hello-world", {
      body: { name: "Functions" },
    });   };

I do not understand what the problem could be since this is just like they did in the docs. and I have no previous experience with edge/cloud functions so I have no idea how I could try to find a solution. I have not found any good recourses online either.


Solution

  • You are trying to invoke a Supabase function from JS, but you haven't added the CORS headers to your function. This link explains how to add CORS headers to your Supabase function.

    Add this code to your _shared folder in cors.ts.

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

    Then, make your function like this:

    import { serve } from 'https://deno.land/[email protected]/http/server.ts'
    import { corsHeaders } from '../_shared/cors.ts'
    
    serve(async (req) => {
      // This is needed if you're planning to invoke your function from a browser.
      if (req.method === 'OPTIONS') {
        return new Response('ok', { headers: corsHeaders })
      }
    
      try {
    
        // Function code here ...
    
        return new Response(JSON.stringify(data), {
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }, // Be sure to add CORS headers here too
          status: 200,
        })
      } catch (error) {
        return new Response(JSON.stringify({ error: error.message }), {
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }, // and here
          status: 400,
        })
      }
    })