Ahmad Raza
Ahmad Raza

Reputation: 139

Database operations and changes not working in Supabase Edge Functions

Any database operation I perform inside an edge function is not working as expected. For example, if I insert a record, it will not persist to the database or if I select, it returns 0 records. I don't know what I'm missing. Following code is an insertion operation, it does not throw any error and changes are not persisted to the database.

Note: Things work as expected in local environment.


import Joi from "npm:joi";
import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';

Deno.serve(async (req) => {
  let form;
  form  = await req.json();
  const validator = Joi.object({
    name: Joi.string().required(),
    email: Joi.string().required().email(),
    company: Joi.string(),
    message: Joi.string().required().min(128).max(1024),
  });

  try {
    const validation = validator.validate(form);
    if (validation.error) {
      throw ({ msg: validation.error?.toString()?.replace("ValidationError: ", "") });
    }

    const supabase = createClient(
      Deno.env.get("SUPABASE_URL"),
      Deno.env.get("SUPABASE_ANON_KEY"),
      {
        global: {
          headers: {
            Authorization: `Bearer ${req.headers.get('Authorization')!}`,
          },
        }
      }
    );

    await supabase.from("query").insert({
      name: form?.name,
      email: form?.email,
      company: form?.company,
      message: form?.message
    });

    return new Response(
      JSON.stringify({
        success: true
      }),
      {
        headers: { "Content-Type": "application/json" }
      }
    );
  } catch (error) {
    return new Response(
      JSON.stringify({
        name: form?.name || '',
        email: form?.email || '',
        company: form?.company || '',
        message: form?.message || '',
        error: error?.msg || 'Something went wrong!'
      }),

      { status: error?.msg ? 400 : 500, headers: { "Content-Type": "application/json" } },
    );
  }
});

Upvotes: 0

Views: 392

Answers (1)

Ahmad Raza
Ahmad Raza

Reputation: 139

Actually, I wasn't capturing error from return value and was expecting that promise will through error. So actually error was related to RLS and captured using returned value.

const { error } = await supabase.from("query").insert({
  name: form?.name,
  email: form?.email,
  company: form?.company,
  message: form?.message
});

if (error) {
  console.error(error); // or throw error
}

Error was:

{
  code: "42501",
  details: null,
  hint: null,
  message: 'new row violates row-level security policy for table "query"'
}

I managed to fix it by creating and RLS policy that allows user connecting to supabase to insert a new row on query table.

Upvotes: 0

Related Questions