https://supabase.com/ logo
Join Discord
Powered by
# help-and-questions
  • Managed Supabase, does Auth scale?
    l

    la fusew

    02/15/2023, 4:18 PM
    I'm working on a r/place style of web experiment (). Where a lot of users (hopefully dozens of thousand) will connect and create a user account during a limited amount of time (the event will last 2 weeks). so 2 question in one. Does supabase allows me to authenticate user in services that are completely decoupled from supabase ? (e.g: a Websocket service reading/writing in a Redis db) And let's say money isn't a problem: Does managed supabase would be able to scale for a lot of user logging in and registering at the same time ? (e.g a few thousand per min) Thanks in advance, I hope I was precise enough!
  • Troubles with SQL function return type
    l

    lildripka

    02/15/2023, 4:55 PM
    Hi! I don't have any experience in writing SQL functions so i'm stuck with defining correct return type. I wrote this code and tried to run int in SQL Editor:
    Copy code
    create or replace function test()
    returns setof table("country" countries.country_name, "location" locations.street_address, "postal_code" locations.postal_code)
    language sql
    as $$
      select
      countries.country_name,
      locations.street_address,
      locations.postal_code
      from locations
      join countries using (country_id)
      where countries.region_id = 1
      order by countries.country_name asc;
    $$;
    I also tried to execute it without brackets after table, but it didn't help. So, how to define return type correctly (ideally with custom column names)?
    a
    g
    • 3
    • 8
  • Best practices for updating multiple tables upon a user action?
    d

    DYELbrah

    02/15/2023, 5:22 PM
    Hello team, I'm currently using NextJS + Supabase and am contemplating how much logic should be placed on the client vs server vs db when processing any transaction. As an example, in a commerce app, when a user buys an item. I need to update a stock table, quote table, and possibly others in one go. Is there a best practice for this? I know I could use DB triggers/functions to handle certain updates, or I could of course simply handle the updates in the server calling the supabase api multiple times. Any rules of thumb or preferences?
    a
    • 2
    • 3
  • Is this approach secure?
    f

    fast

    02/15/2023, 5:32 PM
    Hey there I am currently building a web app with NextJS. I am using supabase for all the auth stuff. I'm very new to supabase in general, that's why I was wondering if my approach is secure? Basically what I want to achieve is, the user sends a request to the server with his access token in the body. The server is then checking the access token. If it is invalid, the server sends an 401 Unauthorized error, but if its a valid access token, the server takes the user Id or more specific the sub from the "user_metadata.sub" object and performs changes. So I was wondering if this is secure. Check my code below ⤵️ Client:
    Copy code
    const session = await supabase.auth.getSession();
    const accessToken = session.data.session.access_token;
    ⬆️ This is how i get the session and the access token. I then put the accessToken into a normal fetch request to the backend Backend:
    Copy code
    // getUserFromAccessToken, validates if the given access token is valid
    async function getUserFromAccessToken(accessToken) {
        try {
          const supabase_response = await supabase.auth.getUser(accessToken);
          if(supabase_response.error) {
            sendError();
            return;
          }
          return supabase_response.data.user;
        } catch(e) {
          sendError();
          return;
        }
    }
    ⬆️ This is how I check the given access token (ofc this happens on a server not on client side) I then take the sub ID to perform changes for the user Also I wanted to know if I should provide any configuration to the createClient function on the server side cause I saw it sometimes on blog posts? For example ⤵️
    Copy code
    {
      auth: {
        autoRefreshToken: false,
        persistSession: false
      }
    }
    Let me know if that's secure
    a
    • 2
    • 14
  • Simple Like mechanic
    a

    andrevenancio

    02/15/2023, 5:49 PM
    I'm building a website that has videos and the user should be able to load the initial 10 videos and see which ones they already liked. Load the next 10 and also know which ones they liked. Assuming a "videos", "user" and "likes" table, I can think of doing something like this:
    Copy code
    const { data, error } = await supabase
        .from('videos')
        .select(
          `
          id,
          name,
          thumbnail,
          likes:likes(user_id, video_id)
        `
        )
        .order('created_at', { ascending: false });
    
      if (error) throw new Error(error.message);
    But this returns me ALL the users that liked the video and not if I liked it.
    a
    g
    • 3
    • 11
  • How to install pg_sleep extension or otherwise implement 1-5s wait in plpgsql loop?
    u

    8bitdad

    02/15/2023, 5:58 PM
    Greetings, I need to implement a wait in my plpgsql loop, which has led me to pg_sleep. I see in the docs (https://supabase.com/docs/guides/database/extensions) that "You can also install your own SQL extensions directly in the database through our SQL editor" but I of course get an error ("could not open extension control file "/var/lib/postgresql/extension/pg_sleep.control": No such file") when trying to install pg_sleep because the files do not exist. I couldn't find further instructions elsewhere. Has anyone installed this, or other extensions that are not currently pre-installed? Would also be interested in knowledge on best practice here from someone with SLQ experience. Context is I'm trying to avoid 429 from external API I'm calling in a loop in a loader function. I would like to tell it to wait 1s between calls. Might have to experiment with other durations. Will also likely need this functionality in the future for scheduling cron jobs with <1min precision. Seems pg_sleep can solve these problems. Many thanks in advance, this is my first time posting a coding question like this on a Disc
    g
    • 2
    • 4
  • How to have 2 filters where one of them is only needed to return a row
    h

    Hugos

    02/15/2023, 6:04 PM
    I tried chaining .eq()'s but those only return rows when both match, i want them to return if only 1 of them matches
    g
    • 2
    • 1
  • How to pass options in Supabase python client
    m

    mohnish

    02/15/2023, 6:11 PM
    It looks like the default_class is referenced here, but I still cannot figure out how to actually pass options https://github.com/supabase-community/supabase-py/blob/abd1abb0eff990ce0749e40903a2010aa6dde905/supabase/lib/client_options.py#L14
    • 1
    • 2
  • how to allow user to upload images and then download those images...
    r

    rchrdnsh

    02/15/2023, 6:40 PM
    Working in SvelteKit and I'm trying to create a little app that allows a logged in user to upload images and then show them a preview of those images in context, which would mean downloading those images as well, I assume... Trying to work through the problem, and I'm starting with my table, where each row is new 'ad' with an advertiser and ad_name, as well as views and clicks and other things...the ads are going to be a series of images that play in sequential order like a slideshow, so I want to be able to allow the advertiser to upload an image at a time and see a live preview of the ad as they upload the images. So I'm initially trying to tackle the problem by having a text array of the image paths in the sotrage bucket, then upload to both the storage bucket and add to the images array, but not sure how to go about all this... So, the first bit of functionality I'm trying to tackle is to simply download and display the images, and I've got some of it working, but not all. In this function I can download a single image:
    Copy code
    js
    let imageUrl;
    
    const downloadImage = async (path: string) => {
      try {
        const { data, error } = await supabase.storage.from('ads').download(path)
    
        if (error) {
          throw error
        }
    
        const url = URL.createObjectURL(data)
        imageUrl = url
    
      } catch (error) {
        if (error instanceof Error) {
          console.log('Error downloading image: ', error.message)
        }
      }
    }
    ..and it works, but I can't seem to figure out how to make function reusable. The imageUrl variable cannot seem to be swapped out, like so:
    Copy code
    js
    const downloadImage = async (path: string) => {
      try {
        const { data, error } = await supabase.storage.from('ads').download(path)
        let image;
        if (error) {
          throw error
        }
    
        const url = URL.createObjectURL(data)
        image = url
    
        return image
    
      } catch (error) {
        if (error instanceof Error) {
          console.log('Error downloading image: ', error.message)
        }
      }
    }
    I get error:
    a
    s
    d
    • 4
    • 85
  • Supabase py timeout does not increase despite setting timeout limit
    m

    mohnish

    02/15/2023, 7:15 PM
    I am setting timeout limit as such:
    Copy code
    from supabase import create_client, Client
    from supabase.lib.client_options import ClientOptions
    
    client_options = ClientOptions(timeout=60)
    supabase = create_client(SUPABASE_URL, SUPABASE_ANON_KEY, options=client_options)
    However, the function still times out after 5 seconds (the extra 1 second is from the first query run). I am also just doing a simple query querying 5-6 columns from a table. Any idea how I can fix this?
    g
    k
    • 3
    • 16
  • What SQL is this calling under the hood?
    a

    Atrox

    02/15/2023, 7:26 PM
    probably something like
    SELECT name FROM countries LIMIT 1 OFFSET 0
    g
    k
    s
    • 4
    • 6
  • Redirect URLs
    n

    nateland

    02/15/2023, 8:08 PM
    Hey guys! Can someone point me at some documentation, or ELI5 me what this does pls?
    g
    • 2
    • 3
  • Can't log in? Recovery mode? Database locked?
    k

    Ken

    02/15/2023, 8:42 PM
    Hi Everyone, Here's what happened. I was on the free account. I wrote a ton of data to the DB (5.5GB). I went over the free storage. I stopped being able to login. I upgraded to a paid account. I still can't login, admin panel is working. Seems like the DB is still locked in a read only state?
    s
    • 2
    • 6
  • Can't get my plv8 function to validate or work
    r

    Ruzelmania

    02/15/2023, 9:06 PM
    I wrote (what I thought) was a really simple DB function. There is a table called messages and I am trying to write a function (with plv8) that can access a specific message via id, like so: `create or replace function get_message(id int) returns text as $$ var messageText = plv8.execute('select message from messages where id = $1', [ 'id' ]); return messageText; $$ language plv8; Supabase keeps telling me that
    invalid input syntax for type bigint: "id"
    a
    g
    • 3
    • 22
  • Cannot create a foreign data wrapper server
    d

    devx101

    02/15/2023, 9:42 PM
    I'm on the hosted version of supabase and activated the postgres_fdw extension successfully. After this I attempted to create a foreign data wrapper server using the command (credentials changed):
    Copy code
    CREATE SERVER foreign_server
    FOREIGN DATA WRAPPER postgres_fdw
    OPTIONS (host 'test.example.com', dbname 'testdb', port '5432');
    However this command fails with the postgresql error:
    Copy code
    Query 1 ERROR: ERROR:  permission denied for foreign-data wrapper postgres_fdw
    I'm connected to the supabase db with the postgres user, but it appears the postgres_fdw extension is assigned to the
    supabase_admin
    user. Is this why I cannot create a foreign data wrapper server? If so, how can I fix this?
    g
    a
    • 3
    • 8
  • Migrate auth.users from one project to another
    a

    AlanK

    02/15/2023, 10:05 PM
    I've been searching in this channel and with Google and can't find an "up to date" answer. What is the best process for migrating all the auth.users from one project to another.
    s
    k
    • 3
    • 3
  • check if [username] exists in profiles table to use it as a [slug] in the url
    r

    Rasta

    02/15/2023, 10:34 PM
    Hi, i have created a profiles table to use it for the users username in the url, so if they visit for example mysite.com/rasta will check if it exists and fetch the user data or show a 'user not found' message in the page. im using sveltekit so also i created a routes/[username]/page.svelte, with this contents:
    Copy code
    <script>
            import {page} from '$app/stores'
            import { onMount } from 'svelte'
            import { supabaseClient } from '$lib/supabase';
            let found = false;
            const getProfile = async () => {
        
            try {
              const {data, error} = await supabaseClient
                .from('profiles')
                .select('username')
                .eq('username', $page.params.username )
                .single()
        
              if (data) {
                console.log(data);
                found = true
              }
              if (error) {
                console.log(error);
              }
            } catch (error) {
              if (error instanceof Error) {
                alert(error.message)
              }
            } 
            }
            getProfile()
        
        </script>
        
        {#if found}
            <h1>User found</h1>
        {:else}
            <h1>User NOT found</h1>
        {/if}
    this works but not sure if is the best way to do it, the page shows the 'User NOT found' message for a few ms before is confirmed the username exists. is there a proper guide for checking the username and slugs in general or this is a good approach to it?
    a
    • 2
    • 2
  • How to use pg_temp in seed.sql
    u

    user8923

    02/15/2023, 10:53 PM
    I'm tring to create and use functions in my seed.sql that I only use within that file. So I create the functions within the pg_temp schema, but when I attempt to call them I'm getting this error: ERROR: schema "pg_temp" does not exist (SQLSTATE 3F000) What's the reason for this?
    g
    s
    • 3
    • 15
  • hide column in table editor
    r

    Rake

    02/15/2023, 11:04 PM
    I have a list of notes each with a content entry but there are so many of a decent length that make the editor really slow. is there a way to not show the entry on the web editor?
    g
    a
    • 3
    • 55
  • Supabase db gives random fetch errors
    s

    Solemensis

    02/15/2023, 11:08 PM
    Sometimes crud requests are just giving random 400-500 fetch errors when everything should be alright. It felt unreliable at this point. Is something wrong with my project or is it supabase?
    g
    • 2
    • 2
  • Stack depth limit exceeded
    a

    Atrox

    02/15/2023, 11:49 PM
    Copy code
    sql
    create or replace function authorize_by_domain(profile_id uuid, workspace_id uuid) returns boolean as $$
    declare
        user_email text;
        domain text;
        workspace_domain text;
        domain_enabled boolean;
    begin
        select email from profiles where id = $1 into user_email;
        select substring(user_email from position('@' in user_email) + 1) into domain;
        select email_domain, email_domain_enabled into workspace_domain, domain_enabled from workspaces where id = $2;
        return domain_enabled and (domain = workspace_domain);
    end;
    $$ language plpgsql;
    I have the function above to enable joining a workspace based on a user's email and am using this in an RLS policy like
    authorize_by_domain(auth.uid(), id)
    but it's causing a stack overflow and I can't figure out why.
    g
    • 2
    • 2
  • Using supabase in Strapi headless CMS
    j

    JustPatrick

    02/16/2023, 1:14 AM
    Has anyone setup strapi to use supabase? I wanted help in setting this up. #1006358244786196510
    n
    • 2
    • 3
  • Preventing users from double commit?
    u

    Unknown Member

    02/16/2023, 2:35 AM
    Hi, I created an RLS to prevent a user from double committing to a user_requests table, and I am wondering if anyone could help me make sense the policy generated by Postgresql? The rule is: Do not create a new request, if the user has an existing request with status 0 (PENDING), 1 (APPROVED), or 2 (DENIED). I tested it, and it seems to work, but I'm trying to understand what's happening under the hood, why is there a new
    user_requests_1
    table. Is this table persisting, and will this policy cause problems? Hope to have any advice. thanks! ❤️ Supabase ❤️
    Copy code
    ((auth.uid() = user_id) AND (NOT (listing_id IN ( SELECT user_requests_1.listing_id
       FROM user_requests user_requests_1
      WHERE ((user_requests_1.user_id = auth.uid()) AND (user_requests_1.request_status = ANY (ARRAY[0, 1, 2])))))))
    • 1
    • 1
  • Can Supabase handle a 6Million row table?
    k

    Ken

    02/16/2023, 2:49 AM
    Team, About at the end of my patience of Supabase. I am a complete amateur so I admit I may be doing something wrong. I have a historical data set I am trying to make dashboards for. React app front end. Supabase backend. I processed my data with AWS lambda functions and tried to load 6 Million rows (about 20 floats, a jsonb and some varchar columns) and it sort of worked. However, now my DB has crashed or something and has been down for about ~6 hours with no answer to support tickets. Couldn't rely on this system in production. Let me know if I am doing something embarrassingly wrong.
    k
    • 2
    • 9
  • Error from PostgrestBuilder.ts failing to import cross-fetch?
    k

    Kenneth J Hughes

    02/16/2023, 3:07 AM
    I'm trying to connect to a local dev setup, which seemed to have "supabase start" 'ed successfully, but I see the following error in the browser console suggesting failure during import of supabase-js:
    Uncaught SyntaxError: The requested module './../../../../cross-fetch/dist/node-ponyfill.js' does not provide an export named 'default' (at PostgrestBuilder.ts:1:8)
    Any ideas what I might be doing wrong?
  • Select Check to see if exist
    r

    rlee128

    02/16/2023, 3:10 AM
    Are we able to run a select 1 request in flutter to check if a row exist? If not how would we do a check?
    • 1
    • 1
  • Custom JWT & Realtime - Only getting DELETE events
    r

    redlumxn

    02/16/2023, 4:42 AM
    I'm trying to subscribe, via Realtime, to events on one of our tables with RLS enabled. However, I'm only receiving DELETE events and nothing else. I would like to be able to subscribe to
    ALL
    events. FYI - when RLS is disabled on the table, I do get all the events. Our current setup involves the minting of custom JWT with additional claims (see below). We are using
    Supabase Project JWT Secret
    to sign it.
    Copy code
    json
    {
      "sub": "google-apps|user@googleworkspace.com",
      "role": "authenticated",
      "aud": "authenticated",
      "userId": "google-apps|user@googleworkspace.com",
      "iat": 1676519049,
      "exp": 1676522649
    }
    The RLS policy looks like this:
    Copy code
    sql
    CREATE POLICY "ALL"
        ON public.test_table
        AS PERMISSIVE
        FOR ALL
        TO public
        USING ((auth.user_id() = user_id));
    and finally the
    auth.user_id
    function looks like this
    Copy code
    sql
    CREATE OR REPLACE FUNCTION auth.user_id(
        )
        RETURNS text
        LANGUAGE 'sql'
        COST 100
        STABLE PARALLEL UNSAFE
    AS $BODY$
      select nullif(current_setting('request.jwt.claims', true)::json->>'userId', '')::text;
    $BODY$;
    
    ALTER FUNCTION auth.user_id()
        OWNER TO postgres;
    And the actual subscription on the client side:
    Copy code
    typescript
    sbClient
        .channel("test_channel")
        .on(
          "postgres_changes",
          {
            event: "*",
            schema: "public",
            table: "test_table",
          },
          (payload) => {
            console.log("Receive table event...");
            console.log(payload);
          }
        )
        .subscribe((status: string, error: Error) =>
          console.log({ status, error })
        );
    However, I get no other event ie
    INSERT
    or
    UPDATE
    for example. Any pointers? P.S. I can see records being created in the
    realtime.subscription
    table (see screenshot) and
    Replication
    is enabled for the table (see other screenshot).
    w
    g
    • 3
    • 8
  • Error cant fetch http://MyDomain/rest/v1/
    h

    Ho3einvb

    02/16/2023, 5:33 AM
    error
  • How reliable is realtime for Postgres Changes?
    d

    DYELbrah

    02/16/2023, 5:38 AM
    I noticed within the README for realtime, Postgres Changes are in GA status whereas Broadcast and Presence are in Beta. Within my app, I'm only using realtime to listen for Postgres Changes. So far I realtime has worked flawlessly and I haven't had any issues with connection failing or anything along those lines. This begs the question of how reliable connecting to realtime is for postgres changes only. I was reading through Gary's discussion here and it seemed very interesting, but am not sure if I even need to implement something like this: https://github.com/supabase/supabase/discussions/5641 Will I perhaps experience more errors or issues with listening to postgres changes once my app grows/listens to more connections at once? Thanks!
    g
    • 2
    • 1
  • `Connecting to Default Project` takes forever
    l

    LA

    02/16/2023, 7:18 AM
    Hi, I have cloned and installed the packages by running
    npm install
    and I ran
    npm run dev
    . I opened the studio project. It is showing
    connect to default project
    for a long time. Did I miss any step?
    s
    • 2
    • 3
1...133134135...230Latest