'Edge Function Returned a Non-2xx Status Code': Fix (Lovable)

Lovable or supabase-js shows 'Edge Function returned a non-2xx status code' and nothing else. Read the real error body, check secrets, auth and CORS, and add a way to see these failures in production.

"Edge Function returned a non-2xx status code" is a generic wrapper from supabase-js. It only tells you the function answered with an error status. To fix it, read the real response body from the error object, then open the function's logs to see why it failed. The usual causes are a missing secret, a 401 from auth, an uncaught exception in your code, or CORS headers missing on the error response.

This message shows up in apps built with Lovable, Bolt and similar AI app builders, because they wire the front end to Supabase Edge Functions for things like payments, emails and AI calls. The builder often hides the details, so you see a toast with this one line. The steps below get you from that line to the cause. Sources used are the Supabase docs on Edge Function 500 errors, 401 errors and status codes.

Step 1: Read the Real Error From the Response

supabase.functions.invoke returns an error object. For non-2xx responses it is a FunctionsHttpError, and the response is on error.context. Log it.

import { FunctionsHttpError } from "@supabase/supabase-js";

const { data, error } = await supabase.functions.invoke("create-checkout", {
  body: { plan: "pro" },
});

if (error instanceof FunctionsHttpError) {
  const status = error.context.status;
  const body = await error.context.json(); // a body can be read once
  console.error("function failed", status, body);
}

Now you have two facts: the status code and whatever message the function returned. In Lovable, ask the builder to add this logging, or paste the snippet where the call is made. The status code tells you where to look next.

Step 2: Match the Status Code to a Cause

  • 401: the request was rejected for auth. Go to Step 3.
  • 404: the function name is wrong or it was never deployed.
  • 500: your code threw, or it returned 500 on purpose. Go to Step 4.
  • 546 or timeouts: the function ran out of resources or took too long. Check the Supabase error codes page.
  • 0 or a CORS message in the browser: go to Step 5.

If the status is a 4xx that your own code returns, the message in the body is usually specific, such as "missing field" or "invalid plan". Fix the request or the validation.

Step 3: Fix 401 Errors Without Turning Off Auth

By default Supabase checks for a valid JWT before your function runs. A 401 can come from two places: the platform check, or your own code returning 401. The Supabase 401 guide explains how to tell them apart.

Common causes:

  • The user is signed out or the session expired, so no valid token is sent.
  • You call the function with plain fetch and forget the Authorization: Bearer <token> header. supabase.functions.invoke adds it for you when the client has a session.
  • The call comes from a server or a webhook that has no user token.

Do not switch JWT verification off for a function that real users call just to make the error go away. If a webhook must call the function, verify the caller yourself, for example with a signature check, as in Stripe Webhook Failures: Debug and Fix in Production.

Step 4: Open the Function Logs for 500 Errors

A 500 means an unhandled error in your function, or your own code returning 500. In the Supabase dashboard, open Edge Functions, pick the function, and open its Logs. Repeat the failing action in the app and look for the new entry. Per the Supabase 500 guide, the log has the error thrown by your code.

The most common cause in Lovable projects is a missing secret. The function reads a key such as STRIPE_SECRET_KEY or OPENAI_API_KEY, but the value was never added in Lovable's secrets settings or in Supabase. The code then fails on the first call that needs it.

const key = Deno.env.get("STRIPE_SECRET_KEY");
if (!key) {
  return new Response(
    JSON.stringify({ error: "STRIPE_SECRET_KEY is not set" }),
    { status: 500, headers: { ...corsHeaders, "Content-Type": "application/json" } },
  );
}

With the CLI, set a secret with supabase secrets set STRIPE_SECRET_KEY=... and check names with supabase secrets list. Names are case sensitive.

Other frequent causes: calling a third-party API that returns an error you did not handle, parsing a body that is empty, and a database insert blocked by row level security. For the last one see Supabase RLS Errors in Production: Debug Empty Results.

Step 5: Add CORS Headers to Error Responses Too

A browser only lets your front end read a response if the CORS headers are present. Many examples add them to the success response and forget the error response. The browser then reports a CORS failure and hides the real status.

const corsHeaders = {
  "Access-Control-Allow-Origin": "https://yourapp.com",
  "Access-Control-Allow-Headers":
    "authorization, x-client-info, apikey, content-type",
};

Deno.serve(async (req) => {
  if (req.method === "OPTIONS") {
    return new Response("ok", { headers: corsHeaders });
  }
  try {
    // ... your logic
    return new Response(JSON.stringify({ ok: true }), {
      headers: { ...corsHeaders, "Content-Type": "application/json" },
    });
  } catch (e) {
    return new Response(JSON.stringify({ error: String(e) }), {
      status: 500,
      headers: { ...corsHeaders, "Content-Type": "application/json" },
    });
  }
});

Every return path, including errors, uses corsHeaders. For the preflight details, read Supabase Edge Function CORS Error: Fix the Preflight.

Step 6: Make Failures Visible After You Publish

Once the app is live, users hit paths you never tried. A function that works in the editor preview can fail for real users because of a different secret, a different origin or a different data shape. A toast that says "non-2xx" disappears, and you never learn it happened.

Three habits help:

  • Return a clear JSON error body from every failure path, with a short code.
  • Log errors with console.error including the user id and the input shape, never secrets.
  • After each publish, run the key flows once, such as sign up and checkout, and watch the logs while you do.

For a wider setup see Find Production Bugs Before Users Report Them.

How Relia Helps

Relia watches the users, APIs and database of a live product, and it supports Supabase and edge functions. When failing calls start after a publish, it joins the signals into one incident described in plain words and shows which users were affected. When a stack trace exists it gives a fix plan with the file and line, and after a deploy it checks whether the fix worked. It can also monitor key pages and endpoints for uptime. Relia does not change your code. Try the live demo or start on the Free plan.

FAQ

What does "Edge Function returned a non-2xx status code" mean?

It means your function responded with a status outside 200 to 299. supabase-js wraps every such response in this one message. The status and body are on error.context.

How do I see the actual error body?

Check that the error is a FunctionsHttpError, then read await error.context.json(). A response body can be read only once, so store the result.

Why does it work in the Lovable preview but fail after publishing?

Usually a secret or setting is missing in the published environment, or the allowed origin in your CORS headers does not include the new domain. Compare secrets and origins between both.

Is it safe to disable JWT verification to fix a 401?

Not for functions that users call, because anyone could then call them. Keep verification on and fix the missing token, or verify webhook callers in your own code.

Where are Edge Function logs?

In the Supabase dashboard under Edge Functions, then the function's Logs tab. Look at the entry that matches the time of your failed request.

All guides