https://supabase.com/ logo
Join Discord
Powered by
# help-and-questions
  • How to define RLS in "code"?
    m

    moarwick

    04/14/2023, 2:04 AM
    My SQL game is not strong. I'm learning the Supabase CLI approach to local development, defining tables via migration files. But how does one express the RLS policies in this way? Not finding any docs on it 🤔
    g
    • 2
    • 6
  • How to call supabse client outside React function component?
    r

    rommyarb

    04/14/2023, 2:44 AM
    I'm using
    @supabase/auth-helpers-react
    in my Next.js project. I have initialized the supabase client url & anon key in the
    _app.tsx
    file, and in my React function component I can call supabase client like this:
    Copy code
    js
    import { useSupabaseClient } from '@supabase/auth-helpers-react';
    
    function MyComponent(){
      const supabase = useSupabaseClient(); // <-- like this
      // ...
    }
    What if I want to use this initialized supabase client outside function component? Do I need to initialize new supabase client with
    createClient()
    ? Thank you in advance!
  • Approach to secure API DB operations with the client
    b

    bombillazo

    04/14/2023, 2:49 AM
    I have CRUD operations that require specific validations, authentication checks and data processing that using the Supabase client alone could not handle. To give an example, lets say there is an
    invitations
    table. Inserting to this table isn't as simple as adding a record. It requires checking the inviter has access to the target account, the status field in that table cannot be set directly by the client, and ideally some related tables are updated as well so it preferably runs in a transaction. Ideally, one has an API endpoint
    POST
    for
    /invitations
    to handle this internally, but that is controlled by PostgREST. So the question is, what is the Supabase "philosophy" or approach to using the Supabase client on the front-end? Is it mainly used for simple actions and Admin CRUD operations with the PostREST endpoints, and for "real" backend logic one has to define RPCs? Should I define another "equivalent" parallel operation to simulate what I would normally do as a POST
    invitations
    endpoint in a regular API?
  • Edge function 504 Gateway timeouts
    n

    nnet3

    04/14/2023, 2:50 AM
    I made a post about this previously but did not receive any help. Locally running edge functions would result in a 504 after 60 seconds of an open connection. I had more luck when running it remotely, but now experiencing 504s after 3.3 minutes. I know the edge function itself is still executing, but the connection from the client to the server is timing out. Is there a way to increase the timeout? The timeouts are quite large because I am waiting on a GPT4 response which is slow! Potentially would need to somehow break these requests out or run some background process. Any thoughts here? Thanks
  • Snowflakes and Timestamps
    d

    dperolio

    04/14/2023, 4:02 AM
    Is there any way to set a default id field value to a JS function return value? In particular, I'm looking to use something akin to Twitter snowflakes, i.e.
    97549189629636608
    And is there any way to set a field value to default as
    Date.now()
    (i.e. the number of milliseconds elapsed since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC.)? Or do I just have to set the field as a number with a default of 0 or something and generate/set them myself with JS?
    g
    • 2
    • 1
  • Supabase realtime with custom JWT
    s

    squallsama

    04/14/2023, 4:05 AM
    I'm using self-hosted Supabase with flutter app + custom jwt token signed with Supabase jwt. Everything fine if I use init with following method:
    Copy code
    await Supabase.initialize(
                url: <supabase_url>,
                anonKey: <anon_key>,
                headers: {
                  'Authorization': 'Bearer $userJwtToken',
                });
    But in order to make realtime work I have to pass
    userJwtToken
    again -
    Copy code
    var client = Supabase.instance.client;
        client.realtime.setAuth(userJwtToken);
    Is there any way how can I initialize Supabase with properly initialized realtime ? I saw doc in https://supabase.com/docs/guides/realtime/extensions/postgres-changes#custom-tokens but for flutter I'm not sure that it's a working solution
    g
    • 2
    • 7
  • Could not find the function in the schema cache (RPC)
    p

    panduram

    04/14/2023, 4:39 AM
    Hi I have created a postgres function using the supabase ui with 4 parameters. function definition is
    Copy code
    begin
      insert into public.rooms (created_by_id, room_manager_id, room_name, room_key,starting_balance,room_open,player_id_list)
      values (
        cbi,
        cbi,
        rn,
        rk,
        sb,
        true,
        ARRAY[] :: uuid[]
      );
    
      UPDATE public.players
      SET room_id_list = array_append(room_id_list, (SELECT id FROM public.rooms WHERE room_name = rn))
      WHERE id = cbi;
    end;
    public.rooms table has this row level policy check :
    (auth.uid() = room_manager_id)
    with role as
    authenticated
    for
    INSERT
    . When i am calling this function from a nextjs api route function like this,
    Copy code
    const cbi : string= session.user.id
    const rn : string= req.body.room_name
    const rk : string= req.body.room_key
    const sb : number= req.body.starting_balance
    let { data, error } = await supabase.rpc("create_room", {cbi, rn, rk, sb} );
    if (error) console.error("rpc crete_room error : ",error);
    else console.log("rpc create_room success : ",data);
    This gives me an error ,
    Copy code
    {
      code: 'PGRST202',
      details: 'Searched for the function public.create_room with parameter cbi or with a single unnamed json/jsonb parameter, but no matches were found in the schema cache.',
      hint: null,
      message: 'Could not find the function public.create_room(cbi) in the schema cache'
    }

    https://cdn.discordapp.com/attachments/1096293573193895946/1096293573374255155/image.png▾

    j
    g
    j
    • 4
    • 4
  • Using email api (customer.io or sendgrid)
    j

    jj_sessa

    04/14/2023, 6:42 AM
    Hello Im looking to send the supabase emails through a email api like customer.io or sendgrid just for template control, is this possible?
    g
    • 2
    • 1
  • enable superuser
    a

    AMZ7860

    04/14/2023, 7:18 AM
    i need to enable superuser for my postgresql database, is there any way to do it? getting error => must be superuser to alter superuser roles or change superuser attribute
    n
    • 2
    • 2
  • make database calls atomic
    d

    divrai

    04/14/2023, 7:58 AM
    I want to insert "question" into database and image provided with question in the "storage". If one fails I want both calls to fail. How to do that?
    Copy code
    ts
      const { currentUser } = useAuth();
      const [questionValue, setquestionValue] = useState("");
      const [fileValue, setfileValue] = useState<File | null>(null);
      const [subjectValue, setsubjectValue] = useState<string | null>(null);
      const [moduleValue, setmoduleValue] = useState<string | null>(null);
      const [marksValue, setmarksValue] = useState<number | "">(1);
    
      const submitHandler = async (event: React.FormEvent<HTMLFormElement>) => {
        event.preventDefault();
        setLoading(true);
    
        const file = fileValue;
        const fileExt = file ? file.name.split(".").pop() : null;
        const fileName = file ? `${Math.random()}.${fileExt}` : null;
        const filePath = file ? `images/${fileName}` : null;
    
        try {
          if (!questionValue || !subjectValue || !moduleValue || !marksValue) {
            throw new Error("Please fill all the fields");
          }
    
          const authorValue = userDetails?.id;
          const orgNameValue = userDetails?.org_name;
    
          const question = {
            question: questionValue,
            marks: marksValue,
            module: moduleValue,
            subject: subjectValue,
            author: authorValue,
            org_name: orgNameValue,
            question_image: filePath,
          };
    
          const { error: uploadQuestionError } = await supabase
            .from("questions")
            .insert([question]);
    
          if (uploadQuestionError) {
            throw uploadQuestionError;
          }
    
          if (fileValue && filePath && file) {
            const { data: fileUploadData, error: fileUploadError } =
              await supabase.storage.from("question_image").upload(filePath, file);
    
            console.log("file uploaded", fileUploadData);
    
            if (fileUploadError) {
              throw fileUploadError;
            }
          }
            // success
        } catch (error: any) {
          // log
        }
    n
    • 2
    • 1
  • Google Login Supabase v2.0 x Expo
    i

    ibrahim-ml

    04/14/2023, 8:35 AM
    I am trying to implement google login on my react-native expo project. I can see that there are guides on how to do it for Supabase v1.X. But I can never find any example on how to implement google login using Supabase 2.X. I need help here.
    a
    m
    • 3
    • 2
  • Colima breaks creating new users in local supabase instance
    r

    riccardolardi

    04/14/2023, 8:54 AM
    Minimal demo repository for reproduction: https://github.com/riccardolardi/test-supabase-colima Running Colima with this config:
    Copy code
    PROFILE    STATUS     ARCH       CPUS    MEMORY    DISK     RUNTIME    ADDRESS
    default    Running    aarch64    4       6GiB      60GiB    docker
    And latest
    supabase
    and
    @supabase/supabase-js
    Creation of new users via
    supabase.auth.admin.createUser()
    or
    supabase.auth.signUp()
    will result in following error:
    Copy code
    AuthRetryableFetchError: fetch failed
        at /Users/riccardolardi/Code/test-supabase-colima/node_modules/@supabase/gotrue-js/dist/main/lib/fetch.js:30:16
        at Generator.next (<anonymous>)
        at /Users/riccardolardi/Code/test-supabase-colima/node_modules/@supabase/gotrue-js/dist/main/lib/fetch.js:8:71
        at new Promise (<anonymous>)
        at __awaiter (/Users/riccardolardi/Code/test-supabase-colima/node_modules/@supabase/gotrue-js/dist/main/lib/fetch.js:4:12)
        at handleError (/Users/riccardolardi/Code/test-supabase-colima/node_modules/@supabase/gotrue-js/dist/main/lib/fetch.js:27:40)
        at /Users/riccardolardi/Code/test-supabase-colima/node_modules/@supabase/gotrue-js/dist/main/lib/fetch.js:87:35
        at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
      __isAuthError: true,
      status: 0
    }
    Anyone has an idea what could be happening?
    g
    • 2
    • 2
  • 2FA enrollment after user abandoned an enrollment?
    d

    Dawnmist

    04/14/2023, 9:59 AM
    I'm currently testing 2FA enrollment, and have run into issues. On the first load of the 2FA enrollment page, I was able to get a QR code/secret being returned by
    supabase.auth.mfa.enroll
    . As I was debugging the page, I made some changes and then reloaded it. All subsequent attempts to load the enrollment page result in a null response to the
    supabase.auth.mfa.enroll
    request. If the user abandons their initial 2FA enrollment (e.g. closed tab, navigated elsewhere, etc), what is the application supposed to do to handle the situation when that same user attempts to enroll 2FA a second time?
    t
    g
    • 3
    • 3
  • I've got CORS issue with Edge Functions with local development
    k

    Kevin Tale

    04/14/2023, 10:02 AM
    Hey! I've created an edge function which is correctly deployed and I 'm trying to call it using the browser but I'm getting a CORS Issue. I've followed this guide : https://supabase.com/docs/guides/functions/cors Here's the code :
    Copy code
    typescript
    import 'https://deno.land/x/xhr@0.3.0/mod.ts';
    import { Configuration, OpenAIApi } from 'https://esm.sh/openai@3.2.1';
    import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
    
    const configuration = new Configuration({
      apiKey: Deno.env.get('OPENAI_API_KEY'),
    });
    const openai = new OpenAIApi(configuration);
    
    serve(async (req) => {
      if (req.method === 'OPTIONS') {
        return new Response('ok', { headers: corsHeaders });
      }
      try {
        const { query } = await req.json();
    
        [...]
    
        return new Response(JSON.stringify({ answer }), {
          headers: { ...corsHeaders, 'Content-Type': 'application/json' },
          status: 200,
        });
      } catch (error) {
        return new Response(JSON.stringify({ error: error.message }), {
          headers: { ...corsHeaders, 'Content-Type': 'application/json' },
          status: 400,
        });
      }
    });
    Here's the invocation on the frontend side :
    Copy code
    typescript
      async triggerEdgeFunction() {
        const { data, error } = await supabaseClient.functions.invoke(
          'my-edge-function',
          {
            body: {...},
          }
        );
      }
    And I got a CORS error on this call, and the OPTIONS is getting a 500 error. Anyone got an idea? Thanks for the help!
    r
    • 2
    • 17
  • Edge Functions limitations
    m

    matthieup

    04/14/2023, 10:19 AM
    Hi, I would like to ask if Supabase Edge Functions are subject to limitations. Here is an example of what I am experiencing: I have a list of users, and I would like to enable each user by clicking a button. I am able to enable more than 100 users at the same time. However, when I try to enable more than 50 users, the Edge Function that is triggered to create an Auth user is not starting.
    s
    g
    • 3
    • 5
  • Users cannot Sign Up. url parameter is missing
    n

    nyasinskiy

    04/14/2023, 12:12 PM
    Since yesterday I have this Errors in the logs: 500: Database error saving new user { "component": "api", "error": "failed to close prepared statement: ERROR: current transaction is aborted, commands ignored until end of transaction block (SQLSTATE 25P02): ERROR: url argument is missing (SQLSTATE P0001)", "level": "error", "method": "POST", "msg": "500: Database error saving new user", "path": "/signup", "referer": "", "remote_addr": "", "time": "2023-04-14T12:02:17Z", "timestamp": "2023-04-14T12:02:17Z" }
    g
    s
    • 3
    • 27
  • Merge two queries into one. Searching all posts of friends
    d

    DwarfNinja

    04/14/2023, 12:49 PM
    Is it possible to merge these two queries into one query using something like
    !inner
    ? And bonus question, does doing queries like this impact performance?
    Copy code
    dart
      getAllIdsOfFriends() async {
        var friendIds = await supabase
            .from('friends')
            .select('friend')
            .eq('user', supabase.auth.currentUser!.id);
    
        final List<String> friendIdsList = friendIds.map<String>((obj) => obj['friend'] as String).toList();
        return friendIdsList;
      }
    
      getAllPostsOfFriends() async {
        List<String> friendIdsList = await getAllIdsOfFriends();
    
        var data = await supabase
            .from('timeline')
            .select('*')
            .in_('user', friendIdsList);
        return data;
      }
  • Running Cached Function ???
    r

    RubensNobre

    04/14/2023, 1:35 PM
    Since Supabase start to rebrand dashboard Im facing lot's of errors. Now, everytime I run a SQL function from SQL Editor. Seems like it always re-run the previous function used, then only in second attempt the current functions is correctly executed. Does anybody facing same issue??
    g
    • 2
    • 2
  • Token and refresh page
    f

    funkyj

    04/14/2023, 1:46 PM
    Hi, I use this code const getUser = async () => { { const { data, error } = await supabase.auth.getSession(); if (data.user) { const { data: userWithEmail } = await supabase .from("users") .select() .eq("email", data.user.email) .single(); user.value = { id: userWithEmail.id, email: userWithEmail.email }; console.log("userData", data); } if (error) { return "getuserError", error; } } }; I have trouble with the follow scenario: When i delete the acces token from local storage i get no error that there is not acces token anymore. How can i check this? When i use getUser i do get a 401 error when there is not token anymore but is it also possible to use getSession? Because i would think it would show ma a error when there is not session in local storage?
    g
    • 2
    • 31
  • 204 on update without permission
    n

    Netail

    04/14/2023, 1:47 PM
    Is it correct behaviour that supabase returns a http/204 on a update, while they do not have permission and thus not actually updated? It's weird behaviour as a fetch does return a http/401 if the user has no permission.
    g
    • 2
    • 8
  • createSignedUploadUrl() removed from JS v2?
    f

    felarchondo

    04/14/2023, 2:01 PM
    Hi all! My company is using Supabase for its DB and storage needs. The javascript docs make reference to a createSignedUploadUrl() function, similar to how upload can work on S3 itself - https://supabase.com/docs/reference/javascript/storage-from-createsigneduploadurl However, it seems that this function is no longer available. Is that the actual case or am I holding something wrong (we are using v2.17.0 of the JS SDK)? If it is indeed no longer available, what is the recommended path for client-side secure uploads? My thinking at a high level was to establish folders on a per-user basis, and give each user read/write access only to their folder, but am open to suggestions. Thanks in advance!
    g
    • 2
    • 18
  • What data is fed into Clippy (Dashboard)?
    e

    eyJOdnJHb25uYSI6Imd2VXVwIn0=

    04/14/2023, 3:03 PM
    Would be nice to know this, since I'm serving my app from the EU and have to know how much of my users data is sharing with third-parties. For now I assume that only the Tables definitions is shared?
    g
    • 2
    • 3
  • Connecting to database as `supabase_admin`
    t

    TimurKramar

    04/14/2023, 3:27 PM
    Hi, I have table
    users
    in my public schema owned by
    supabase_admin
    . I started a project from the nextjs-subsription-payments, where by the end this table, and also some other, were created. I would now like to add columns to this table to store more info about users, but as it is owned by
    supabase_admin
    , I don't have the rights to alter it in any way. I need a way to move the ownership to
    postgres
    . Thanks for any tips.
    g
    d
    • 3
    • 9
  • AbortController in Supabase
    r

    Rikka

    04/14/2023, 3:33 PM
    How can I abortController in Supabase. I'm use react-query combine supabase ?
    g
    • 2
    • 2
  • CORS rejection on locally hosted edge functions
    d

    doot0

    04/14/2023, 3:42 PM
    Hi. I've created several locally hosted edge functions but when I attempt to call them from an origin of
    localhost:5173
    I get a CORS rejection, despite me explicitly defining the given CORS headers in https://supabase.com/docs/guides/functions/cors. I'm running
    supabase functions serve --debug
    in order to serve my local functions and the Deno relay instance boots via docker successfully and listens on
    0.0.0.0:8081
    , but requests made to
    localhost:54321/functions/xyz
    (my local supabase instance URL) claim that there is no Access-Control-Allow-Origin' header. Any help or insight would be greatly appreciated. Cheers
    • 1
    • 1
  • invalid input syntax type uuid
    f

    flimsycabbage

    04/14/2023, 3:48 PM
    Hello. I changed my jwt secret and changed all my environment variables etc. Now I get
    Copy code
    invalid input syntax for type uuid:
    when trying to upload to storage. I am using clerk for auth. Please help.
    g
    • 2
    • 5
  • Got a 502 error when sending an email using the browser with Edge Function
    k

    Kevin Tale

    04/14/2023, 3:52 PM
    Hi ! Here's my code :
    Copy code
    typescript
    import { SMTPClient } from 'https://deno.land/x/denomailer@1.6.0/mod.ts';
    import { serve } from 'https://deno.land/std@0.168.0/http/server.ts';
    
    const client = new SMTPClient({
      connection: {
        hostname: 'smtp.postmarkapp.com',
        port: 2525,
        auth: {
          username: '...',
          password: '...',
        },
      },
    });
    
    serve(async (req) => {
      if (req.method === 'OPTIONS') {
        return new Response('ok', {
          headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers':
              'authorization, x-client-info, apikey, content-type',
          },
        });
      }
    
      try {
    
        await client.send({
          from: 'contact@my-domain.com',
          to: 'someone@gmail.com',
          subject: `the subject`,
          content: `hello world!`,
        });
      } catch (error) {
        return new Response(error.message, {
          headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers':
              'authorization, x-client-info, apikey, content-type',
            'Content-Type': 'application/json',
          },
          status: 500,
        });
      }
    
      await client.close();
    
      return new Response(
        JSON.stringify({
          done: true,
        }),
        {
          headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers':
              'authorization, x-client-info, apikey, content-type',
            'Content-Type': 'application/json',
          },
          status: 200,
        }
      );
    });
    The error says on frontend in the headers is
    x-deno-error: {"code":"UNCAUGHT_EXCEPTION","message":"The deployment failed while serving the request."}
    And the logs on the supabase dashboard says :
    Copy code
    Error: invalid cmd
        at SMTPConnection.assertCode (https://deno.land/x/denomailer@1.6.0/client/basic/connection.ts:55:19)
        at SMTPConnection.writeCmdAndAssert (https://deno.land/x/denomailer@1.6.0/client/basic/connection.ts:98:14)
    Does someone have an idea on why this is happening? Thanks!
  • Supabase Studio 2.0: Query performance issue with privilegs
    m

    Michael Ketzer | streamgeist.com

    04/14/2023, 4:37 PM
    It is nice to see, that there are time consuming queries, but it would be great to see the actual queries 😄 Anyone got an idea why I do not have the privilegs? I am the owner of the project.

    https://cdn.discordapp.com/attachments/1096474345276182548/1096474345657868369/Screenshot_2023-04-14_at_18.32.45.png▾

    g
    • 2
    • 6
  • Timestamptz issue
    w

    WalkerJson

    04/14/2023, 5:04 PM
    I am currently seeing an issue with timestamptz fields where the date shows as 1 day prior to the actual date that is being stored. This has only started to happen recently, so I wonder if I need to set a timezone somewhere, or if there is something I need to change? The gif attached should show the date changing. Sorry if this is a basic question..

    https://cdn.discordapp.com/attachments/1096481060520468582/1096481060696621116/Timestamptz.gif▾

  • Rate Limiting Edge Functions
    a

    anggoran

    04/14/2023, 6:05 PM
    Hello I've seen a video from Supabase about rate limiting Edge Functions with Upstash-Redis. My question is if invokers exceed the limit, does Supabase still bill the invocations? Cause the function endpoint is public and anyone can invoke it, I wonder if someone can spam it
    g
    • 2
    • 4
1...179180181...230Latest