Next.js Discord

Discord Forum

Call serverless function from edge function

Unanswered
Lucy posted this in #help-forum
Open in Discord
Hi! I'm trying to call a serverless function from an edge function, because I can return immediately from the initial edge function (to avoid the cold boot) and then use the information in the request to send my response via a webhook from the serverless function. The flow I would like is:

External user POST to edge function
Edge function calls serverless function, but does not await it
Edge function responds to external user
time passes, possibly lots if serverless function is cold
Serverless fires a webhook
Serverless function responds, not that the edge function cares

Currently I have this

// /api/handle.ts
export const config = {
  runtime: "edge",
};
export default async function handler(request: Request) {
  fetch(`https://${process.env.VERCEL_BRANCH_URL}/api/command`, {
    headers: request.headers,
    body: request.body,
    method: request.method,
    credentials: request.credentials,
    cache: request.cache,
    integrity: request.integrity,
    mode: request.mode,
    referrer: request.referrer,
    referrerPolicy: request.referrerPolicy,
    signal: request.signal,
  });
  return new Response(
    JSON.stringify({
      type: 5, // DEFER
    }),
    {
      status: 200,
      headers: {
        "content-type": "application/json",
      },
    }
  );
}


// /api/command.ts
export default async function handler(
  request: VercelRequest,
  response: VercelResponse
) {
  if (await verify(request, response)) {
    if (await handleCommand(request.body, response)) {
      response.status(200).json({});
      return;
    }
  }
  response.status(400).json({});
}

export async function verify(
  request: VercelRequest,
  response: VercelResponse
): Promise<boolean> {
  // stuff happens
  return true;
}

async function handleCommand(
  message: any,
  response: VercelResponse
): Promise<boolean> {
  // stuff happens
  fetch(
    `${WEBHOOK_URL}/${process.env.ID}/${message.id}/`,
    {
      method: "POST",
      body: JSON.stringify({
        content: "Work completed",
      }),
    }
  );
  return true;
}


The problem is, it doesn't appear that the fetch from the edge function is actually received and responded to by the serverless function?

1 Reply

im not exactly sure but fetch in V8 isolates won't be fired once a request life time ends(no await). if it's such a simple reverse-proxy, you might want to use Cloudflare Worker directly, Queue might be usable(im abt to play around with it).