Write data to database after returning response in edge function

Hi.
is it possible for the netlify edge function to do further tasks after sending response to the client. like writing data to a database.

following is the vercel edge function example which has “request”, “event” parameters. which work perfectly. any code inside the event.waitUntil is executed after sending the response.

export default async (request, event) => {
    
    event.waitUntil(
        fetch('https://default-rtdb.europe.firebasedatabase.app/.json',
            {method:"POST", body:JSON.stringify({ "abc": 'abc' })
        })
    )
    
    return new Response('hello world')

};

but Netlify edge function takes two parameters “request” and “context”. there is no event parameter. how can i use ExtendableEvent.waitUntil() or is there any other way.

Could you talk more about your use case? Why not write to database from within the edge function, before sending the response?

Also interested if is possible.

This practice is used in many places when you want to do an operation that is irrelevant to the response so you can respond a bit faster to the client.

The problem I think is that in an edge function once you return a response you can’t execute anymore anything else.

I think I found a way that’s working, you simply need to put your code into setTimeout callback:

Example:


import { createClient } from "https://esm.sh/@supabase/supabase-js";

const SUPA_TOKEN = Deno.env.get('TOKEN')

const options = {
  schema: "public",
  autoRefreshToken: true,
  persistSession: true,
  detectSessionInUrl: true,
};

const supabase = createClient(
  "https://lcspcmmpolegvalxkfsu.supabase.co",
  SUPA_TOKEN,
  options,
);

export default async (request: Request) => {
    setTimeout(async () => { 
        await supabase.from('fsk_email_copy').insert({json: JSON.stringify(
            {
                name: 'test',
                email: 'test',
                message: 'test',
            }
        )})
        }, 7000);
    return Response.json('Hello world', {status: 200})
}

I did put a very high number 7000 to test that it works but in a real scenario, you would put something like 20 or 50.

Hi @andrei0x309 , thanks for sharing that with us.

1 Like