Supabase's edge function is being executed twice, despite only one call being made

I am facing an issue with my edge function in TypeScript at Supabase that connects to our Postgres database and runs a query. The problem is that the function is being executed twice, regardless of whether I run it locally in the CLI or deploy it to production. Strangely, console logging indicates that the entire function is running twice as well. However, when I check the browser console, it only shows one call to the function on button click. Any suggestions on how to fix this?

Below is the HTML code:

<html>
  <head>
    <meta charset="utf-8">
    <title>Invoke Supabase Function</title>
  </head>
  <body>
    <button id="invoke-button">Invoke Function</button>
    <script language="Javascript">
      const apiKey = XXXXX
      const functionEndPoint = 'http://localhost:54321/functions/v1/';

      const inputData = { name: 'Blah' };
      
      const invokeFunction = () => {
        console.log('Called invokeFunction');
        fetch(`${functionEndPoint}`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${apiKey}`
          },
          body: JSON.stringify(inputData)
        })
          .then(response => response.json())
          .then(data => {            
            console.log(data);
          })
          .catch(error => {
            console.error(error);
          });
      };
      
      document.getElementById('invoke-button').addEventListener('click', invokeFunction);
    </script>
  </body>
</html>

And here is the function code:

import * as postgres from 'https://deno.land/x/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6d6c9d5d2c1d4c3d5e6d0968897928894">[email protected]</a>/mod.ts'
import { serve } from 'https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ffcfbebcfbfa1beb8b8a1bf">[email protected]</a>/http/server.ts'
import { createClient } from 'https://esm.sh/@supabase/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a1d2d4d1c0c3c0d2c48ccbd2e1908f92928f90">[email protected]</a>'
import { corsHeaders } from '../_shared/cors.ts'

const databaseUrl = "postgresql://XXXXX"
const pool = new postgres.Pool(databaseUrl, 3, true)

serve(async (_req) => {
  
  
  try {
    // Grab a connection from the pool
    const connection = await pool.connect()

    try {
      // Run a query (its actually a non-deterministic fb function/stored proc)
      console.log("inbound startgame request...")
      const result = await connection.queryObject`SELECT public."newGame"();`
      const rr = result.rows
      console.log(rr)

      // Encode the result as pretty printed JSON
      const body = JSON.stringify(
        rr,
        (key, value) => (typeof value === 'bigint' ? value.toString() : value),
        2
      )

      // Return the response with the correct content type header
      return new Response(
        JSON.stringify(rr),
        { 
          headers: { ...corsHeaders, "Content-Type": "application/json" },
          status: 200,
        },
      )

    } finally {
      // Release the connection back into the pool
      connection.release()
    }
  } catch (err) {
    console.error(err)
    return new Response(String(err?.message ?? err), { status: 500 })
  }

Answer №1

Aha! The secret to fixing the edge function lies in this crucial snippet:

  if (req.method === 'OPTIONS') {
    return new Response('ok', { headers: corsHeaders })
  }

It turns out that browsers initiate a pre-flight request to check if the function supports CORS. If this process is not handled correctly, the function will run twice - first during the pre-flight check and then again during the main call. By including CORS headers in the response as shown above, both runs were successful from the browser's perspective.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for accessing the PR number in a Node.js GitHub Probot listening for the `pull_request` event

I've recently developed a GitHub probot application using nodejs and typescript. Currently, I have set up an event listener for the pull_request event. How can I extract the pr_number from the context object within the probot? The snippet below is fr ...

The issue of HTTP parameters not being appended to the GET request was discovered

app.module.ts getHttpParams = () => { const httpParamsInstance = new HttpParams(); console.log(this.userForm.controls) Object.keys(this.userForm.controls).forEach(key => { console.log(this.userForm.get(key).value) const v ...

The response parser in Angular 7 is failing to function correctly

Hey, I recently updated my Angular from version 4.4 to the latest 7 and after encountering several errors, I was able to get my service up and running. However, I'm facing an issue with my output parser function which is supposed to parse the login re ...

Error: Unable to Locate Module (Typescript with baseUrl Configuration)

Struggling to implement custom paths in my TypeScript project, I keep encountering the "webpackMissingModule" error due to webpack not recognizing my modules. I've attempted various solutions without any success. Any suggestions or ideas? Some packa ...

Tips for expanding third-party classes in a versatile manner using Typescript

tl;dr: Seeking a better way to extend 3rd-party lib's class in JavaScript. Imagine having a library that defines a basic entity called Animal: class Animal { type: string; } Now, you want to create specific instances like a dog and a cat: const ...

Obtain the data from a promise in Angular

I have a function that returns a Promise, and within that Promise, I receive an object in the resolve. Below is the function from my service that is functioning correctly. buscarUsuario(email: string){ return new Promise((resolve, reject) => { this.ht ...

complete() method is not triggered by Observable

Note: I understand that there is a timer observable from rxjs, but for the purpose of this project, I am using it as a proof of concept to enhance my understanding of observables. In my Angular application, I have developed a timer with a start button, a ...

Interact with pgcrypto module using Python

I am looking to utilize pgcrypto functions within Python, specifically px_crypt. However, I am encountering difficulty determining the correct object files to link. Below is the code snippet: #include <Python.h> #include "postgres.h" #include "pg ...

Is there a way to link a particular model table with a designated user table?

Hey everyone, I'm new to stack overflow and this is my first question. I hope it's clear enough for you all to understand. I'm currently working on a budget API using Node.js, Sequelize, Express, and PostgreSQL. The API allows users to add/ ...

Issue encountered when working with interface and Observable during the http parsing process

Visual Studio File Structure Error app(folder) -->employee-list(folder) -->employee-list.component.html -->employee-list.component.ts -->app.component.html -->app.component.ts -->app.module.ts -->employee.json ...

Take out a specific element from an array consisting of multiple objects

I have a specific array structure and I need to remove elements that match a certain criteria. Here is the initial array: const updatedUsersInfo = [ { alias: 'ba', userId: '0058V00000DYOqsQAH', username: '<a href=" ...

Zero-length in Nightmare.js screenshot buffer: an eerie sight

I'm currently working on a nightmare.js script that aims to capture screenshots of multiple elements on a given web page. The initial element is successfully captured, but any subsequent elements below the visible viewport are being captured with a l ...

NodeJS and TypeScript collaborating to manage a limitless AWS S3 bucket in a blank state

Having trouble with my removeObjects function. I'm trying to make it fetch a list of objects from an S3 bucket synchronously and then remove the objects asynchronously. The goal is to repeat this process if the list was truncated until all objects are ...

There is no correlationId found within the realm of node.js

Currently, I am in the process of implementing correlationId functionality using express-correlation-id. I am diligently following the guidelines provided on this page: https://www.npmjs.com/package/express-correlation-id. I have successfully imported the ...

Utilizing conditional types for type narrowing within a function's body: A comprehensive guide

I created a conditional type in my code that constrains the second argument of my class constructor based on the type of the first argument. Although the type checker correctly limits what I can pass to the constructor, I am struggling to get the compiler ...

Typescript: object containing at least one property with the type T assigned

Is there a method to write the HasNumber interface in Typescript without receiving an error due to the fact that the HasNumberAndString interface includes a property that is not of type number? I am looking for a way to require the HasNumberAndString int ...

Angular not triggering event upon changing URL fragment subscription

I'm currently using Angular 13 and attempting to subscribe to the ActivatedRoute 'fragment'. However, I am facing an issue where the subscription only receives a notification when the page initially loads, and does not update when the fragme ...

Applying Multiple Conditions to setCellProps in Material-UI

I am facing an issue with a data-table that is not in a class extending the React.Component, unlike some examples I have come across. My goal is to setCellProps based on certain conditions as outlined below: If utilization is less than or equal to 50, the ...

When a variable is used in Postgresql, the ORDER BY clause is disregarded, but accurate results are returned when the variable value is

After investigating, it seems that the query is always returning rows ordered by id, regardless of the value passed in the sortType variable (verified in console). export async function fetchAnimalList(sortType) { noStore(); try { const areas = aw ...

Authenticating with JWT in Deno

Can someone guide me on generating and authenticating JSON Web Token in Deno? Being a newbie to the Deno environment, I would greatly appreciate a code snippet to kickstart my journey with JWT in Deno. ...