Supabase "Edge Function returned a non-2xx status code": find the real error and fix it

By AI App Medic · Updated · Supabase · Edge Functions · Lovable · Debugging

A button in your app does nothing, or a toast says Edge Function returned a non-2xx status code. In the browser console you find this:

FunctionsHttpError: Edge Function returned a non-2xx status code
    at FunctionsClient.invoke (...)

Lovable shows the same line in its error panel, and the AI assistant tends to answer it by rewriting the CORS block or the whole function. That rarely helps, because the message is not the error. It only says the function was reached and answered with a status of 400 or higher. The real reason is in the response body and in the function logs, and the fix depends entirely on which status came back.

What the message means

supabase.functions.invoke can fail in three different ways, and supabase-js gives each one its own error class:

So if you see the non-2xx message, the network path works. Stop changing URLs and CORS settings until you know the status code.

Step 1: read the real status and body

The response is kept on error.context. Log it once and the guessing ends:

import { FunctionsHttpError } from '@supabase/supabase-js'

const { data, error } = await supabase.functions.invoke('generate-report', {
  body: { projectId },
})

if (error instanceof FunctionsHttpError) {
  const res = error.context
  console.error(
    'generate-report failed',
    res.status,
    res.headers.get('sb-error-code'),
    await res.text()
  )
}

You can also get the same facts without touching code. Open DevTools, Network, click the request to /functions/v1/generate-report, and read the status and the Response tab. If the function returns its own JSON error, it is right there.

Step 2: match the status to a cause

The sb-error-code response header, when present, names the condition directly, which helps when the body is empty.

Step 3: read the function logs at the same timestamp

In the Supabase dashboard open Edge Functions, select the function, then open Invocations for the request list and Logs for everything the function printed. Reproduce the error once, refresh, and read the entry with the matching time. A stack trace, a TypeError or a message from your own console.error is the real error.

If your Lovable app runs on Lovable Cloud instead of a Supabase project you own, the function logs are in the Cloud section of the Lovable editor. The status codes mean the same thing.

Step 4: fix the usual 500 causes

A secret that is not set. Deno.env.get('OPENAI_API_KEY') returns undefined when the secret does not exist in that project, and the first call that uses it throws. Secrets in your local .env or in Lovable's chat are not automatically secrets on the function. Check with the CLI:

supabase secrets list --project-ref <project-ref>
supabase secrets set OPENAI_API_KEY=sk-... --project-ref <project-ref>

Or add it in the dashboard under Edge Functions, Secrets. Names must not start with SUPABASE_; that prefix is reserved, and SUPABASE_URL, SUPABASE_ANON_KEY and SUPABASE_SERVICE_ROLE_KEY are already provided.

A body the function did not expect. await req.json() throws on an empty body or on plain text. Calling the function with GET, or with a body built from a form that is still empty, gives you a 500 instead of a useful 400.

An upstream error passed through as a crash. OpenAI, Resend or Stripe answered 401 or 429, the code assumed success, and reading a missing property threw. Check response.ok on every outbound call and log the upstream body.

A handler that turns all three into clear answers, and keeps CORS headers on errors so the browser does not hide them:

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

function json(body: unknown, status = 200) {
  return new Response(JSON.stringify(body), {
    status,
    headers: { ...corsHeaders, 'Content-Type': 'application/json' },
  })
}

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

  try {
    const apiKey = Deno.env.get('OPENAI_API_KEY')
    if (!apiKey) return json({ error: 'OPENAI_API_KEY is not set for this function' }, 500)

    let input: { prompt?: string }
    try {
      input = await req.json()
    } catch {
      return json({ error: 'Request body must be JSON' }, 400)
    }
    if (!input.prompt) return json({ error: 'prompt is required' }, 400)

    const upstream = await fetch('https://api.openai.com/v1/responses', {
      method: 'POST',
      headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
      body: JSON.stringify({ model: 'gpt-4.1-mini', input: input.prompt }),
    })
    if (!upstream.ok) {
      console.error('OpenAI error', upstream.status, await upstream.text())
      return json({ error: `Upstream API returned ${upstream.status}` }, 502)
    }
    return json(await upstream.json())
  } catch (err) {
    console.error('Unhandled error', err)
    return json({ error: 'Internal error' }, 500)
  }
})

The function still fails when something is wrong, but now the status and the message say what, and the logs have the details. Keep upstream error bodies in the logs rather than in the response, since they can include account details.

If the function queries the database with the user's token, an empty result or a permission error may be RLS doing its job. Test the same query as that user before you blame the function.

Step 5: fix a 503 boot error

A 503 means the code never ran. The logs usually show the reason as the first line of the failed boot: an import that could not be fetched, a module that does not exist under that version, or a syntax error. Run it locally to see the same failure with a full trace:

supabase functions serve generate-report --env-file supabase/.env.local

Pin versions in your imports (npm:stripe@17 rather than an unpinned URL), avoid Node packages that need native threads, such as sharp, and redeploy with supabase functions deploy generate-report. Watch the deploy output: a bundling error there is the same problem, caught earlier.

Step 6: fix 504 and 546

Both mean the work is too big for one request. For a 504, put a timeout on outbound calls with AbortSignal.timeout(30000) so you fail with a clear message, stream long AI responses back instead of waiting for the full text, or start the job, return 202 right away, and finish it with EdgeRuntime.waitUntil() while the client polls a status row. For a 546, stop loading whole files or large tables into memory: page through rows, and read files from Storage in parts or process them somewhere with more memory.

The same pattern applies on Vercel. If your AI route times out there instead, see Vercel 504 FUNCTION_INVOCATION_TIMEOUT.

Step 7: make the app show the real message

Wrap invoke once and use the wrapper everywhere. The next failure then shows prompt is required instead of the generic line:

import { FunctionsHttpError, FunctionsFetchError } from '@supabase/supabase-js'

export async function callFunction<T>(name: string, body?: unknown): Promise<T> {
  const { data, error } = await supabase.functions.invoke(name, { body })
  if (!error) return data as T

  if (error instanceof FunctionsHttpError) {
    const text = await error.context.text()
    let message = text
    try { message = JSON.parse(text).error ?? text } catch {}
    console.error(`[${name}] ${error.context.status}`, text)
    throw new Error(message || `${name} failed with status ${error.context.status}`)
  }
  if (error instanceof FunctionsFetchError) {
    throw new Error(`Could not reach ${name}. Check CORS and the project URL.`)
  }
  throw error
}

If the fetch branch fires instead, the request is being blocked before your code sees it. That is covered in Edge Function CORS errors in Lovable.

Prevention

FAQ

Why does error.message always say the same thing?

supabase-js puts a fixed message on FunctionsHttpError and keeps the actual response on error.context. That is a normal fetch Response, so you read it with await error.context.json() or await error.context.text(). Until you log that, every failure looks identical.

Is this a CORS problem?

Usually not. When CORS blocks the request the browser never hands the response to your code, and supabase-js raises FunctionsFetchError with Failed to send a request to the Edge Function. A non-2xx error means the response arrived. The exception is a function that crashes before it adds CORS headers: then the browser may report CORS even though the real problem is a 500.

Do I need to redeploy after setting a secret?

Supabase makes secrets set with the CLI or the dashboard available to deployed functions without a redeploy. If the function still behaves as if the value is missing, check the exact name, check that you set it in the same project the app calls, and redeploy once to rule out an old version.

It works when I test it in the dashboard but fails from the app. Why?

The dashboard test sends whatever body and headers you typed, often with a service key. The app sends the signed-in user's token and the body your front end builds. Compare the two requests: a different body shape, a missing field or a user without the right rows under RLS are the usual differences.

What does status 546 mean?

It is a Supabase status for a function stopped by a resource limit, reported as WORKER_RESOURCE_LIMIT (earlier WORKER_LIMIT). Hosted functions get 256 MB of memory and 2 seconds of CPU time per worker. Loading a whole file or a large result set into memory is the usual cause.

Related guides