neil_ruaro
neil_ruaro

Reputation: 506

CORs error when calling a deployed edge function in supabase from the browser

I have an edge function deployed with the following code:

import { serve } from "server"
import * as cryptojs from "crypto-js";

import { config } from "dotenv";

// Load the environment variables from .env file
await config();

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

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 {

    ...
    ... 
    ...

    return new Response(
      JSON.stringify(data), {
        status: 200,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      }
    )
  } catch (error) {
    return new Response(
      JSON.stringify({ error: error.message || error.toString() }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      }
    );
  }
})

As you can see, corsHeaders is applied to enable invocation from the browser which is called using the supabase libary:

const response = await supabase.functions.invoke(
                "retrieve-payment-link", {
                    body: {
                        id: payment_link_id,
                    }
                }
            );

and was deployed with the following command: npx supabase functions deploy retrieve-payment-link --import-map supabase/functions/import_map.json and yet I'm still having this error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource. Running in local doesn't have any issues, only in production. How do I fix this?

Upvotes: 0

Views: 1152

Answers (2)

Safeer Ahmad
Safeer Ahmad

Reputation: 21

I encountered that issue recently as well. I resolved it by setting the headers on the backend like this:

    Deno.serve(async (req) => {
    
        const headers: Record<string, string> = {
            "Content-Type": "application/json",
        };

        headers["Access-Control-Allow-Origin"] = "*";
        headers["Access-Control-Allow-Methods"] =
            "GET, POST, PUT, DELETE, OPTIONS";
        headers["Access-Control-Allow-Headers"] = "Content-Type, Authorization";
        headers["Access-Control-Allow-Credentials"] = "true";

        if (req.method === "OPTIONS") {
            // Handle preflight requests
            return new Response(null, { status: 204, headers });
        } 
    
// Remaining code

    return new Response(
            JSON.stringify({ data}),
            {
                headers,
            },
        );

}

From the frontend side, I didn't use Supabase.functions.invoke because it consistently throws a CORS error, which I suspect is a bug in Supabase. Instead, I made requests to the Supabase Edge function directly like this:

         let requestOptions = {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization:"Bearer "+ token,
          },
        };
    
        const options = {
        ...requestOptions,
        body: JSON.stringify({ amount }),
      };
      const res = await fetch(
        "edge_function_url",
        options
      );

  const extractData = await res.json();

I hope, this code will be helpful.

Upvotes: 0

Asier Alcaide
Asier Alcaide

Reputation: 3

In local, the Docker Containers were not updated after the Supabase CLI update. Plase run supabase stop and supabase start to restart and download the containers again.

Upvotes: 0

Related Questions