Skip to main content

Supabase RLS for a multi-vendor marketplace: buyer, vendor and admin policies that hold up

Written by DevoraXReviewed by Sameem Amjad, Founder & Lead Architect EngineerLast updated Based on public sources and platform documentation (guide)

In a multi-vendor marketplace on Supabase, one order can hold lines from several vendors, so the order and its lines need different owners. Give every order line its own vendor_id that the database copies from the product, keep the delivery address in its own table, store roles in tables users cannot write, check vendor membership through a security definer function in a private schema, and let a vendor's status decide whether its products are on sale. Then test as each buyer, each vendor, an admin and a signed-out visitor, and expect exact row counts.

Who this is for: Founders and developers with a marketplace on Supabase, whether Lovable or Bolt generated it or it was written by hand, who need vendors, buyers and admins kept apart.

What a marketplace database has to enforce

A multi-vendor marketplace has three kinds of signed-in user writing to the same tables. Buyers create orders. Vendors list products and fulfil the lines of those orders that are theirs. An admin approves vendors and sees everything. On Supabase the browser talks to the database directly with the public key, so every one of those rules has to live in Postgres, as row-level security (RLS) policies and grants. A rule that only exists in the interface is a hidden button, not a permission.

What makes a marketplace harder than a typical SaaS app is the basket. One checkout can hold a shirt from Vendor X and two scarves from Vendor Y. The order belongs to the buyer, but each line belongs to a different vendor, and Vendor X must be able to ship its shirt to the buyer's address without seeing what the buyer bought from Vendor Y or what the whole basket cost. Most multi-tenant RLS tutorials assume one owner per row. Here, one purchase has several.

This guide is about that data model and its policies. If the Security Advisor says a table has RLS switched off, start with RLS disabled in public. If requests fail with error 42501, see permission denied for table. Come back here when RLS is on and the question is who should see which order.

The table below is the target. Every SQL snippet in this guide was run on PostgreSQL 18.3 with Supabase's anon, authenticated and service_role roles and its auth.uid() function recreated locally. It was not run on a live Supabase project.

Who may do what, table by table
TableBuyerVendor memberAdminSigned out
vendorsRead active vendorsRead active vendors and its own; rename its ownRead all; approve or suspend, which puts its products on or off saleRead active vendors
vendor_membersNo accessRead its own teamAdd and remove membersNo access
productsRead active products of active vendorsAdd, edit and archive its own, visible to it even while pending; never move one to another vendorRead and edit allRead active products of active vendors
ordersCreate and read own ordersNo accessRead allNo access
order_itemsAdd lines to own unpaid order; read all lines of own ordersRead and fulfil its own lines onlyRead all; any status changeNo access
order_shippingAdd to own unpaid order; read ownRead the address once it has a paid line in the orderRead allNo access
vendor_payout_accountsNo accessRead its own; never writeRead all; never write from the browserNo access

Why generated marketplace schemas leak

RLS filters rows. It does not filter columns, and it knows nothing about baskets. Three consequences catch most marketplaces.

First, a policy decides whether a whole row is visible. If vendors need the buyer's address and the address lives on orders, any policy that shows Vendor X that order also shows its total, its payment status and anything else stored on it. The fix is in the schema, not the policy: put the part of the order a vendor needs in its own table.

Second, the rule that a vendor sees order lines for its own products needs to know which vendor a line belongs to. If that is only knowable by joining order_items to products to vendor_members, every read pays for the join, and a generated policy often drops the vendor condition altogether to make an error go away.

Third, the role has to come from somewhere the user cannot edit. AI builders often store it in a role column on profiles that the user's own update policy covers, or in user metadata, which Supabase's RLS guide says "can be modified by authenticated end users" (read 30 November 2026). Either way, a user can promote themselves.

Two background facts from Supabase's docs matter before you write anything. As of November 2026, the RLS guide says "Views bypass RLS by default because they are usually created with the postgres user." And since 30 October 2026, new tables in the public schema of every project no longer receive Data API grants automatically, according to Supabase's announcement. A new table that returns 42501 may be missing a grant rather than a policy.

Common mistakes in AI-generated marketplace schemas

These turn up again and again in marketplaces generated by AI builders, and each one below was reproduced on the test database used throughout this guide.

  • vendor_id taken from the client. The browser sends vendor_id with a new order line or product, and the insert policy only checks that someone is signed in. A buyer can attribute a line to the wrong vendor, which misroutes payouts, and a vendor can list products under a competitor's shop. The database should copy vendor_id from the product, and any vendor_id the client does send must be checked against the caller's memberships.
  • A role in user_metadata or in an editable profile column. A policy that tests auth.jwt() -> 'user_metadata' ->> 'role' = 'admin' hands every order to anyone who edits their own metadata. On the test database, buyer B with an admin role in user_metadata saw all 3 orders instead of her 1. Supabase's Security Advisor reports this as 0015_rls_references_user_metadata, at ERROR level.
  • A "vendors can read orders" policy with no vendor condition. Checking only that the caller belongs to some vendor gives every vendor every order line. On the test database, Vendor X saw all 4 order lines, including buyer B's belt from Vendor Y, instead of its own 2.
  • Vendor approval that changes nothing. A vendors.status column that the product policies and the checkout never read is decoration: a pending vendor's products go on sale the moment they are listed, and a suspended vendor keeps selling. The storefront policy and the pricing trigger both have to check that the vendor is active.
  • Views without security_invoker. A vendor dashboard view that joins order lines, products and addresses runs with its owner's rights unless told otherwise. Vendor X read 4 rows and 4 addresses through such a view; after setting security_invoker = true it read 2 rows and 1 address.
  • A membership policy that queries its own table. Writing the vendor_members policy as a subquery on vendor_members fails with "infinite recursion detected in policy", error 42P17, and the usual reaction is to loosen the policy until the error stops. The fix is a security definer helper, in step 2.
  • Prices and totals sent by the browser. If the client writes the unit price or the total, a buyer can pay what they like. The database, or server code, has to set them from the product.
  • The secret key in the admin screen. An admin page that calls Supabase with the service_role key, or a key starting sb_secret_, ships that key to every browser that loads it, and Supabase's API keys page says a secret key "bypasses every Row Level Security policy you have".
  • Policies without TO. A policy with no TO clause applies to public, which includes signed-out visitors.
Two policies to search your project for. Neither belongs in a marketplace.SQL
-- Mistake: any vendor reads every order line in the marketplace.
create policy "vendors can read order items" on public.order_items
  for select to authenticated
  using (exists (select 1 from public.vendor_members where user_id = (select auth.uid())));

-- Mistake: the admin check reads user_metadata, which the user can edit.
create policy "admins read all orders" on public.orders
  for select to authenticated
  using ((auth.jwt() -> 'user_metadata' ->> 'role') = 'admin');

How to check the marketplace you already have

Start with what Supabase already measures. The Security Advisor (in the dashboard under Advisors, or supabase db advisors in the CLI, as of November 2026) flags tables without RLS, always-true policies, security definer views and policies that read user metadata. Our Supabase RLS checker runs a similar read-only check from one query you paste into the SQL editor.

Neither knows your marketplace, so read the policies on the order tables yourself. The query below lists them. For each SELECT policy on order_items, ask two questions. Does it name the vendor of this line, through vendor_id and the caller's memberships? Does it name the buyer, through the parent order? A policy that only checks that auth.uid() is not null, that auth.role() is authenticated, or that the caller belongs to any vendor is a leak. Roles shown as {public} mean the policy has no TO clause.

Then run the impersonation tests from step 6 against a copy of your project, with real user ids from auth.users. Row counts higher than they should be are the clearest signal you will get.

List the marketplace policies, and any views that skip the caller's RLSSQL
-- Every policy on the marketplace tables: who it applies to and what it checks.
select tablename, policyname, cmd, roles, qual as using_expression, with_check
from pg_policies
where schemaname = 'public'
  and tablename in ('vendors', 'vendor_members', 'vendor_payout_accounts', 'products',
                    'orders', 'order_items', 'order_shipping')
order by tablename, cmd, policyname;

-- Views in public that run with their owner's rights instead of the caller's.
select c.relname as view_name
from pg_class c
join pg_namespace n on n.oid = c.relnamespace
where n.nspname = 'public'
  and c.relkind = 'v'
  and not coalesce(
    (select lower(o.option_value) in ('true', 'on', 'yes', '1')
       from pg_options_to_table(c.reloptions) as o
      where o.option_name = 'security_invoker'),
    false);

Step 1: a schema where ownership is in the data

Four decisions do most of the work.

Roles live in tables the user cannot write. Being a buyer is the default for any signed-in user. Being a vendor is a row in vendor_members, which only an admin or server code adds. Being an admin is a row in private.admins, in a schema the Data API does not expose. Supabase's column privileges page recommends this shape: "RLS policies in combination with a dedicated table for handling user roles" (read 30 November 2026). Nothing on profiles decides access.

Every order line carries its own vendor_id. It duplicates products.vendor_id on purpose. The vendor policy becomes a check on an indexed column of the line itself instead of a join through products, and the line keeps its vendor even if the catalogue changes later. The database fills it in, as step 4 shows.

The address a vendor ships to sits in order_shipping, apart from orders. A vendor gets the shipping row for orders where it has a paid line, and never the orders row, so it never sees the rest of the basket or its payment status.

Payout details sit in vendor_payout_accounts, not on vendors. The storefront reads vendors and has no reason to read a Stripe account id. That table is read-only from the browser and written by server code when Stripe reports changes, which is the territory of Stripe Connect marketplace payments.

The Multi-Vendor Marketplace Development page describes the same principle on Afriva, a DevoraX client's fashion marketplace on Next.js 15 and Supabase: row-level security and database triggers keep shoppers to their own orders and sellers to orders for their own products, and the database sets every price. The schema below is a teaching example written for this guide, not Afriva's.

The tables, with an index on every column a policy filters onSQL
-- Roles live in tables users cannot write: private.admins and public.vendor_members.
create schema if not exists private;

create table private.admins (
  user_id uuid primary key references auth.users (id) on delete cascade,
  added_at timestamptz not null default now()
);

create table public.profiles (
  id uuid primary key references auth.users (id) on delete cascade,
  display_name text,
  created_at timestamptz not null default now()
);

create table public.vendors (
  id uuid primary key default gen_random_uuid(),
  name text not null,
  status text not null default 'pending'
    check (status in ('pending', 'active', 'suspended')),
  created_at timestamptz not null default now()
);

create table public.vendor_members (
  user_id uuid not null references auth.users (id) on delete cascade,
  vendor_id uuid not null references public.vendors (id) on delete cascade,
  role text not null default 'staff' check (role in ('owner', 'staff')),
  primary key (user_id, vendor_id)
);

-- Payout details sit in their own table, so the storefront never reads them.
create table public.vendor_payout_accounts (
  vendor_id uuid primary key references public.vendors (id) on delete cascade,
  stripe_account_id text,
  payouts_enabled boolean not null default false,
  updated_at timestamptz not null default now()
);

create table public.products (
  id uuid primary key default gen_random_uuid(),
  vendor_id uuid not null references public.vendors (id),
  name text not null,
  price_cents integer not null check (price_cents >= 0),
  stock integer not null default 0 check (stock >= 0),
  is_active boolean not null default true,
  created_at timestamptz not null default now()
);

create table public.orders (
  id uuid primary key default gen_random_uuid(),
  buyer_id uuid not null default auth.uid() references auth.users (id),
  status text not null default 'pending_payment'
    check (status in ('pending_payment', 'paid', 'cancelled', 'refunded')),
  created_at timestamptz not null default now()
);

-- The part of the order a vendor needs to ship, split from the order itself.
create table public.order_shipping (
  order_id uuid primary key references public.orders (id) on delete cascade,
  recipient_name text not null,
  address text not null,
  phone text
);

create table public.order_items (
  id bigint generated always as identity primary key,
  order_id uuid not null references public.orders (id) on delete cascade,
  product_id uuid not null references public.products (id),
  vendor_id uuid not null references public.vendors (id),
  quantity integer not null check (quantity > 0),
  unit_price_cents integer not null check (unit_price_cents >= 0),
  status text not null default 'awaiting_payment'
    check (status in ('awaiting_payment', 'to_ship', 'shipped', 'delivered', 'cancelled')),
  created_at timestamptz not null default now()
);

-- Index every column a policy filters on.
create index on public.vendor_members (vendor_id);
create index on public.products (vendor_id);
create index on public.orders (buyer_id);
create index on public.order_items (order_id);
create index on public.order_items (vendor_id);
create index on public.order_items (product_id);

Step 2: membership checks through security definer helpers

Policies on several tables need the same two answers: which vendors does the caller belong to, and is the caller an admin. Both come from tables the caller cannot read freely, and vendor_members has its own policy that needs the first answer, which is where the recursion error comes from. A security definer function answers both questions with its owner's rights, so the lookup is not filtered by the policies it serves.

Supabase's RLS guide (read 30 November 2026) sets the rules for these functions, and the snippet follows them. Set search_path = '' and schema-qualify every name, because otherwise "a caller can point an unqualified name at their own object and run it with the function owner's privileges". Keep them out of exposed schemas, because "a security definer function in an exposed schema is callable over the Data API with the creator's privileges"; the private schema is not exposed unless you add it in the API settings. Revoke execute from public, then grant it to the roles whose policies call it.

One detail came out of testing: grant usage on private to service_role as well. Server code with the secret key bypasses RLS, but its updates still fire the guard triggers from step 4, and those call private.is_admin(). Without that grant, the simulated payment webhook's update failed with "permission denied for schema private".

Two helpers in a private schema: the caller's vendors, and whether the caller is an adminSQL
-- Helper functions: security definer, pinned search_path, in a schema the API does not expose.
create function private.is_admin()
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
  select exists (
    select 1 from private.admins
    where user_id = (select auth.uid())
  );
$$;

create function private.my_vendor_ids()
returns setof uuid
language sql
stable
security definer
set search_path = ''
as $$
  select vendor_id from public.vendor_members
  where user_id = (select auth.uid());
$$;

revoke execute on function private.is_admin(), private.my_vendor_ids() from public, anon;
-- service_role too: server code fires the triggers that call is_admin().
grant usage on schema private to authenticated, service_role;
grant execute on function private.is_admin(), private.my_vendor_ids() to authenticated, service_role;
The per-row variant many tutorials show: correct, but called once for every row a query scansSQL
create function private.is_vendor_member(p_vendor_id uuid)
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
  select exists (
    select 1 from public.vendor_members
    where vendor_id = p_vendor_id
      and user_id = (select auth.uid())
  );
$$;

revoke execute on function private.is_vendor_member(uuid) from public, anon;
grant execute on function private.is_vendor_member(uuid) to authenticated;

Three trade-offs come with them. A security definer function skips RLS inside its body, so it must only ever return facts about the caller, keyed on auth.uid(), never on an argument the caller controls. A bug in one of these helpers is a bug in every policy that calls it. The bypass also depends on ownership: Supabase notes that "a security definer function only skips RLS when its owner can". Here the owner is the role that owns the tables, and PostgreSQL exempts a table's owner from its RLS unless FORCE ROW LEVEL SECURITY is set. The test database used an owner that was neither a superuser nor allowed to bypass RLS, to confirm the helpers still work on that basis alone.

The second function, is_vendor_member(vendor_id), reads well in a policy, but it takes a value from the row, so Postgres has to call it once for every row it scans. my_vendor_ids() takes nothing from the row, so Postgres runs it once per query and compares each line against the result. The performance section has the numbers from the test database. Keep is_vendor_member for checks that touch one row, and use the set-returning form in SELECT policies.

Step 3: grants first, then one policy per command

Grants decide whether a role may touch a table or column at all; policies decide which rows. Supabase's RLS guide describes these as two separate checks, and "a missing grant raises a 42501 error before any policy runs". Because grants on new tables are no longer automatic, write both.

The grants below revoke everything from anon and authenticated on the marketplace tables and grant back exactly what the policies need. Signed-out visitors get SELECT on vendors and products and nothing else, so an anonymous request for orders is refused outright instead of returning an empty list. Inserts and updates are granted per column. A buyer may insert order_id, product_id and quantity into order_items and nothing more, so a request that includes unit_price_cents or vendor_id fails before any policy is consulted; step 4 explains why that matters. service_role keeps full grants, because it bypasses RLS but not grants.

The policies come next, then a view for the vendor's order queue. What each part does is explained after the code.

Grants: what each role may touch at all, column by column for writesSQL
-- Grants decide which operations and columns a role may touch at all; policies then pick rows.
revoke all on public.profiles, public.vendors, public.vendor_members,
  public.vendor_payout_accounts, public.products, public.orders,
  public.order_shipping, public.order_items
  from anon, authenticated;

-- Signed-out visitors: the storefront only.
grant select on public.vendors, public.products to anon;

-- Signed-in users: reads everywhere (policies filter the rows) ...
grant select on public.profiles, public.vendors, public.vendor_members,
  public.vendor_payout_accounts, public.products, public.orders,
  public.order_shipping, public.order_items
  to authenticated;

-- ... and writes only to the columns a person may set.
grant update (display_name) on public.profiles to authenticated;
grant update (name, status) on public.vendors to authenticated;
grant insert (user_id, vendor_id, role), delete on public.vendor_members to authenticated;
grant insert (vendor_id, name, price_cents, stock, is_active) on public.products to authenticated;
grant update (name, price_cents, stock, is_active) on public.products to authenticated;
grant insert (buyer_id) on public.orders to authenticated;
grant insert (order_id, recipient_name, address, phone) on public.order_shipping to authenticated;
grant insert (order_id, product_id, quantity) on public.order_items to authenticated;
grant update (status) on public.order_items to authenticated;

-- Server code (secret key) keeps full access; it bypasses RLS but still needs grants.
grant all on public.profiles, public.vendors, public.vendor_members,
  public.vendor_payout_accounts, public.products, public.orders,
  public.order_shipping, public.order_items
  to service_role;

alter table public.profiles enable row level security;
alter table public.vendors enable row level security;
alter table public.vendor_members enable row level security;
alter table public.vendor_payout_accounts enable row level security;
alter table public.products enable row level security;
alter table public.orders enable row level security;
alter table public.order_shipping enable row level security;
alter table public.order_items enable row level security;
Policies for every marketplace table, each with TO and WITH CHECK where rows are writtenSQL
-- One policy per command, each role an OR branch, every policy TO a role.

-- profiles
create policy "profiles: own, or all for admins" on public.profiles
  for select to authenticated
  using (id = (select auth.uid()) or (select private.is_admin()));

create policy "profiles: update own" on public.profiles
  for update to authenticated
  using (id = (select auth.uid()))
  with check (id = (select auth.uid()));

-- vendors
create policy "vendors: storefront sees active" on public.vendors
  for select to anon
  using (status = 'active');

create policy "vendors: active, own, or all for admins" on public.vendors
  for select to authenticated
  using (
    status = 'active'
    or id in (select private.my_vendor_ids())
    or (select private.is_admin())
  );

create policy "vendors: members and admins update" on public.vendors
  for update to authenticated
  using (id in (select private.my_vendor_ids()) or (select private.is_admin()))
  with check (id in (select private.my_vendor_ids()) or (select private.is_admin()));

-- vendor_members: only admins (or server code) change who belongs to a vendor
create policy "vendor_members: own team, or all for admins" on public.vendor_members
  for select to authenticated
  using (vendor_id in (select private.my_vendor_ids()) or (select private.is_admin()));

create policy "vendor_members: admins add" on public.vendor_members
  for insert to authenticated
  with check ((select private.is_admin()));

create policy "vendor_members: admins remove" on public.vendor_members
  for delete to authenticated
  using ((select private.is_admin()));

-- vendor_payout_accounts: read-only in the browser, written by server code
create policy "payout accounts: members and admins read" on public.vendor_payout_accounts
  for select to authenticated
  using (vendor_id in (select private.my_vendor_ids()) or (select private.is_admin()));

-- products: shoppers see a product only while it and its vendor are both active
create policy "products: storefront sees active" on public.products
  for select to anon
  using (
    is_active
    and exists (
      select 1 from public.vendors v
      where v.id = products.vendor_id and v.status = 'active'
    )
  );

create policy "products: active, own, or all for admins" on public.products
  for select to authenticated
  using (
    (
      is_active
      and exists (
        select 1 from public.vendors v
        where v.id = products.vendor_id and v.status = 'active'
      )
    )
    or vendor_id in (select private.my_vendor_ids())
    or (select private.is_admin())
  );

create policy "products: vendors add to their own shop" on public.products
  for insert to authenticated
  with check (vendor_id in (select private.my_vendor_ids()));

create policy "products: vendors edit own, admins edit all" on public.products
  for update to authenticated
  using (vendor_id in (select private.my_vendor_ids()) or (select private.is_admin()))
  with check (vendor_id in (select private.my_vendor_ids()) or (select private.is_admin()));

-- orders: the buyer and admins; vendors never read this table
create policy "orders: buyer's own, or all for admins" on public.orders
  for select to authenticated
  using (buyer_id = (select auth.uid()) or (select private.is_admin()));

create policy "orders: buyer creates own" on public.orders
  for insert to authenticated
  with check (buyer_id = (select auth.uid()));

-- order_items: the buyer of the order, the vendor of the item, admins
create policy "order_items: buyer, item's vendor, admins" on public.order_items
  for select to authenticated
  using (
    order_id in (select id from public.orders where buyer_id = (select auth.uid()))
    or vendor_id in (select private.my_vendor_ids())
    or (select private.is_admin())
  );

create policy "order_items: buyer adds to own unpaid order" on public.order_items
  for insert to authenticated
  with check (
    order_id in (
      select id from public.orders
      where buyer_id = (select auth.uid()) and status = 'pending_payment'
    )
  );

create policy "order_items: item's vendor or admins update" on public.order_items
  for update to authenticated
  using (vendor_id in (select private.my_vendor_ids()) or (select private.is_admin()))
  with check (vendor_id in (select private.my_vendor_ids()) or (select private.is_admin()));

-- order_shipping: the buyer, vendors with a paid item in the order, admins
create policy "order_shipping: buyer, paid vendors, admins" on public.order_shipping
  for select to authenticated
  using (
    order_id in (select id from public.orders where buyer_id = (select auth.uid()))
    or order_id in (
      select order_id from public.order_items
      where vendor_id in (select private.my_vendor_ids())
        and status <> 'awaiting_payment'
    )
    or (select private.is_admin())
  );

create policy "order_shipping: buyer adds to own unpaid order" on public.order_shipping
  for insert to authenticated
  with check (
    order_id in (
      select id from public.orders
      where buyer_id = (select auth.uid()) and status = 'pending_payment'
    )
  );
A vendor order queue that runs with the caller's rightsSQL
-- A vendor's order queue: one row per line to ship, with the address once paid.
create view public.vendor_queue
with (security_invoker = true) as
  select oi.id, oi.order_id, p.name, oi.quantity, oi.status,
         s.recipient_name, s.address
  from public.order_items oi
  join public.products p on p.id = oi.product_id
  left join public.order_shipping s on s.order_id = oi.order_id
  where oi.vendor_id in (select private.my_vendor_ids());

grant select on public.vendor_queue to authenticated;

Every policy names its role with TO, and wraps auth.uid() and private.is_admin() in a select, so Postgres evaluates them once per query instead of once per row. Supabase's performance guide recommends both. Where buyers, vendors and admins all read a table, one SELECT policy carries three OR branches. Separate permissive policies for the same role and command would return the same rows, but the Performance Advisor flags them as 0006_multiple_permissive_policies, because each one is evaluated.

Shoppers see a product only while the product is active and its vendor's status is active, so an admin's decision takes effect at once. A pending vendor can prepare its catalogue without anything going on sale, and suspending a vendor takes all its products off the storefront; the vendor itself and admins still see them through their own branches. Suspension stops new sales, not existing orders: a suspended vendor can still read and ship lines that were already paid for. If suspension should freeze fulfilment too, add the same status check to the order_items update policy.

The cross-vendor case lives in the order tables. A vendor reads order_items where vendor_id is one of its own, so in a basket shared with Vendor Y it sees only its own line. It reads order_shipping only for orders where it has a line past awaiting_payment, so an address reaches a vendor once the order is paid. It never reads orders. A buyer reads every line of their own orders, whoever sells them.

WITH CHECK on every insert and update stops a row being written, or moved, outside the caller's reach. A buyer cannot add lines to someone else's order or to an order that is already paid, and a vendor cannot list a product under another vendor's id.

The view joins lines, products and addresses for a vendor's order queue. It is created with security_invoker = true (PostgreSQL 15 and later) so the caller's policies apply to every table it reads, and its where clause keeps a vendor who also shops on the marketplace from seeing their own purchases in the queue. As Vendor X, it returns the shirt from order 1 with its address, and the shirt from unpaid order 3 with no address.

Step 4: prices, vendor ids, statuses and payout fields the browser cannot set

Some values must never come from the browser, whatever row they are on. Each gets the mechanism that suits it.

Price and vendor on an order line. The trigger price_order_item() copies vendor_id and price_cents from the product when the line is inserted, refuses archived products and products whose vendor is not active, and starts every line at awaiting_payment. With the column grants from step 3, a client cannot even send those values. This is why the database, not the browser, sets prices: the browser runs on the buyer's computer, and anything it sends can be edited before it leaves. On the test database, buyer A's attempt to insert a line at 1 cent failed with "permission denied for table order_items", and the same insert without a price came back with Vendor Y's id and the scarf's real price of 3,000 cents. The trigger could fill columns buyer A had no grant for, because Postgres checks the columns a statement names. The payment itself follows the same rule, which the security checklist covers.

Moving a product to another vendor. products.vendor_id has an insert grant but no update grant, so a vendor chooses its own shop when listing and can never change it afterwards.

Status transitions. WITH CHECK sees only the new row, so it cannot express that shipped may only follow to_ship. A BEFORE UPDATE trigger can, because it sees both versions. guard_order_item_status() lets a vendor move its own lines from to_ship to shipped and from shipped to delivered, and nothing else; admins and server code may make any change, such as a cancellation. guard_vendor_status() does the same for vendor approval: a vendor may rename itself, but only an admin changes its status. The triggers are not security definer, so current_user is the caller: authenticated for a signed-in user's request, service_role for server code.

Payout fields. Nobody in the browser has an insert or update grant on vendor_payout_accounts. Server code writes it with the secret key, typically from Stripe's account webhooks; Stripe Connect marketplace payments covers that side.

Triggers: the database prices each line and decides who may change which statusSQL
-- 1. The database prices every line and records whose item it is.
--    Archived products, and products of a pending or suspended vendor, are not for sale.
create function private.price_order_item()
returns trigger
language plpgsql
set search_path = ''
as $$
begin
  select p.vendor_id, p.price_cents
    into new.vendor_id, new.unit_price_cents
  from public.products p
  join public.vendors v on v.id = p.vendor_id and v.status = 'active'
  where p.id = new.product_id and p.is_active;

  if not found then
    raise exception 'product % is not for sale', new.product_id;
  end if;

  new.status := 'awaiting_payment';
  return new;
end;
$$;

create trigger order_items_price
  before insert on public.order_items
  for each row execute function private.price_order_item();

-- 2. Vendors move their items forward one step; admins and server code may do more.
create function private.guard_order_item_status()
returns trigger
language plpgsql
set search_path = ''
as $$
begin
  if new.status is distinct from old.status
     and current_user = 'authenticated'
     and not private.is_admin()
     and (old.status, new.status) not in (('to_ship', 'shipped'), ('shipped', 'delivered'))
  then
    raise exception 'order item status cannot go from % to %', old.status, new.status
      using errcode = '42501';
  end if;
  return new;
end;
$$;

create trigger order_items_status_guard
  before update of status on public.order_items
  for each row execute function private.guard_order_item_status();

-- 3. Only an admin approves or suspends a vendor.
create function private.guard_vendor_status()
returns trigger
language plpgsql
set search_path = ''
as $$
begin
  if new.status is distinct from old.status
     and current_user = 'authenticated'
     and not private.is_admin()
  then
    raise exception 'only an admin can change a vendor''s status'
      using errcode = '42501';
  end if;
  return new;
end;
$$;

create trigger vendors_status_guard
  before update of status on public.vendors
  for each row execute function private.guard_vendor_status();

revoke execute on function private.price_order_item(),
  private.guard_order_item_status(), private.guard_vendor_status()
  from public, anon, authenticated;

Supabase's column privileges page (read 30 November 2026) calls them "an advanced feature" and warns that "Restricted roles cannot use the wildcard operator (*) on the affected table." Here SELECT stays granted on whole tables and only inserts and updates are limited, so select * still works. What breaks is a client that sends the whole row back on update, including vendor_id or unit_price_cents: that request now fails with 42501. Send only the fields that changed.

If column grants feel too easy to forget, the alternative is a trigger that rejects changes to protected columns. It costs more code, and that code has to change whenever the table does.

Step 5: admin access without the secret key in the browser

An admin is an ordinary signed-in user with a row in private.admins. The admin screens use the same publishable key as the rest of the app. Every policy has a (select private.is_admin()) branch, so the admin's own session reads all orders, lines and payout accounts, and the guard triggers let an admin make status changes vendors cannot. Nothing in the admin's browser is more powerful than the admin's own login, and deleting the row from private.admins takes effect on that user's next query.

Adding an admin is a one-line insert you run in the SQL editor. There is deliberately no policy that lets anyone insert into private.admins from the app: on the test database, buyer A's attempt failed with "permission denied for table admins".

Some admin actions move money: refunds, releasing payouts, changing a connected account. Those belong in server code, such as an Edge Function, that verifies the caller's session, checks that the user is in private.admins, and only then uses the secret key, which never leaves the server. Supabase's API keys page says never to put a secret key in a web page or a shipped app, and never to use one in a browser, "even on localhost".

If you prefer the role in the user's token, Supabase's RLS guide says raw_app_meta_data "cannot be updated by the user, so it's a good place to store authorization data". The alternative is_admin() below reads it. The trade-off is timing: a token carries the claims it was issued with, so promoting or removing an admin takes effect only when that user's token is refreshed, while the table version takes effect at once. On the test database, buyer B with an admin role in app_metadata saw 3 orders, and with the same role in user_metadata saw only her own 1.

Make someone an admin, from the SQL editorSQL
-- Make someone an admin: run in the SQL editor (as postgres), never from the app.
insert into private.admins (user_id)
values ('00000000-0000-0000-0000-0000000000e5');
Alternative is_admin(): read the role from app_metadata, which users cannot editSQL
-- Alternative: read the admin flag from app_metadata, which users cannot edit.
create or replace function private.is_admin()
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
  select coalesce((select auth.jwt() -> 'app_metadata' ->> 'role') = 'admin', false);
$$;

Step 6: test every role, including signed-out visitors

Supabase's RLS guide (read 30 November 2026) says: "Until the suite passes, you don't know whether the policies do what you intended." The quickest test is SQL that impersonates each person with set local role and set local request.jwt.claim.sub, inside a transaction you roll back. Run it in psql or the SQL editor, against a copy of your project if it holds real data.

The test data: Vendor X sells a shirt and has an archived tote. Vendor Y sells a scarf and a belt. Vendor Z is a pending applicant's shop. Order 1 is buyer A's, paid, with one shirt from Vendor X and two scarves from Vendor Y. Order 2 is buyer B's, paid, with a belt from Vendor Y. Order 3 is buyer A's, unpaid, with one shirt from Vendor X. Write the expected counts down before running anything; the table shows what came back, which matched what we expected.

Impersonate one person and count what each table returnsSQL
-- One block per person. Change the id, run, compare with the table below.
begin;
set local role authenticated;
set local request.jwt.claim.sub = '00000000-0000-0000-0000-0000000000c3';  -- vendor X

select
  (select count(*) from public.vendors)                as vendors,
  (select count(*) from public.products)               as products,
  (select count(*) from public.orders)                 as orders,
  (select count(*) from public.order_items)            as order_items,
  (select count(*) from public.order_shipping)         as shipping,
  (select count(*) from public.vendor_payout_accounts) as payout_accounts;

rollback;
The same check for a signed-out visitorSQL
-- A signed-out visitor: the storefront tables answer, the order tables refuse.
begin;
set local role anon;
select
  (select count(*) from public.vendors)  as vendors,
  (select count(*) from public.products) as products;
rollback;

begin;
set local role anon;
select count(*) from public.orders;  -- ERROR: permission denied for table orders
rollback;
The cross-vendor case: Vendor X opens an order it shares with Vendor YSQL
-- Vendor X opens order 1, which also holds two scarves from Vendor Y.
begin;
set local role authenticated;
set local request.jwt.claim.sub = '00000000-0000-0000-0000-0000000000c3';

select oi.id, p.name, oi.quantity, oi.unit_price_cents, oi.status, s.address
from public.order_items oi
join public.products p on p.id = oi.product_id
left join public.order_shipping s on s.order_id = oi.order_id
where oi.order_id = '30000000-0000-0000-0000-000000000001';

select count(*) from public.orders
where id = '30000000-0000-0000-0000-000000000001';  -- 0: vendors never read orders

rollback;
Writes that must fail, and one that must touch only the caller's own lineSQL
-- Buyer A sends her own price: ERROR permission denied for table order_items
begin;
set local role authenticated;
set local request.jwt.claim.sub = '00000000-0000-0000-0000-0000000000a1';
insert into public.order_items (order_id, product_id, quantity, unit_price_cents)
values ('30000000-0000-0000-0000-000000000003', '20000000-0000-0000-0000-000000000003', 1, 1);
rollback;

-- Buyer A adds a line to buyer B's order: ERROR new row violates row-level security policy
begin;
set local role authenticated;
set local request.jwt.claim.sub = '00000000-0000-0000-0000-0000000000a1';
insert into public.order_items (order_id, product_id, quantity)
values ('30000000-0000-0000-0000-000000000002', '20000000-0000-0000-0000-000000000003', 1);
rollback;

-- Vendor X marks all of order 1 shipped: UPDATE 1, her line only
begin;
set local role authenticated;
set local request.jwt.claim.sub = '00000000-0000-0000-0000-0000000000c3';
update public.order_items set status = 'shipped'
where order_id = '30000000-0000-0000-0000-000000000001'
returning id, vendor_id, status;
rollback;

-- Vendor X skips a step: ERROR order item status cannot go from to_ship to delivered
begin;
set local role authenticated;
set local request.jwt.claim.sub = '00000000-0000-0000-0000-0000000000c3';
update public.order_items set status = 'delivered' where id = 1;
rollback;

-- The applicant approves her own pending vendor: ERROR only an admin can change a vendor's status
begin;
set local role authenticated;
set local request.jwt.claim.sub = '00000000-0000-0000-0000-0000000000f6';
update public.vendors set status = 'active'
where id = '10000000-0000-0000-0000-000000000003';
rollback;
Vendor status: suspend one vendor, let a pending one list a product, then look as a shopperSQL
-- Vendor status: a pending or suspended vendor's products leave the storefront.
begin;

-- The applicant lists a lamp while Vendor Z is still pending.
set local role authenticated;
set local request.jwt.claim.sub = '00000000-0000-0000-0000-0000000000f6';
insert into public.products (vendor_id, name, price_cents)
values ('10000000-0000-0000-0000-000000000003', 'Lamp', 5000);

-- An admin suspends Vendor Y.
set local request.jwt.claim.sub = '00000000-0000-0000-0000-0000000000e5';
update public.vendors set status = 'suspended'
where id = '10000000-0000-0000-0000-000000000002';

-- A signed-out visitor now sees Vendor X and its shirt, nothing else.
set local role anon;
select
  (select count(*) from public.vendors)  as vendors,
  (select count(*) from public.products) as products;

-- Buyer A tries to order Vendor Y's belt: ERROR product ... is not for sale
set local role authenticated;
set local request.jwt.claim.sub = '00000000-0000-0000-0000-0000000000a1';
insert into public.order_items (order_id, product_id, quantity)
values ('30000000-0000-0000-0000-000000000003', '20000000-0000-0000-0000-000000000004', 1);

rollback;
Row counts each person saw on the test database. The last four rows are after an admin suspends Vendor Y and pending Vendor Z lists a lamp.
Personvendorsproductsordersorder_itemsorder_shippingpayout accounts
Buyer A232320
Buyer B231110
Vendor X240211
Vendor Y230221
Admin343432
Applicant (pending Vendor Z)330000
Signed out (anon)23permission deniedpermission deniedpermission deniedpermission denied
Signed out, Vendor Y suspended, Vendor Z pending with a lamp11permission deniedpermission deniedpermission deniedpermission denied
Buyer A, same state112320
Vendor Y while suspended230221
Applicant with a lamp, Vendor Z still pending220000

Read the numbers against the data. Vendor X sees 4 products because its archived tote is visible to it but not to shoppers. It sees 2 order lines, its shirts in orders 1 and 3, and only 1 shipping row, because order 3 is unpaid. Vendor Y sees 2 shipping rows because it has paid lines in orders 1 and 2. The applicant sees 3 vendors because her pending shop is visible to her and to admins, not to shoppers. In the cross-vendor query, Vendor X opening order 1 gets 1 line, not 2, and 0 rows from orders.

The status rows show approval doing its job. With Vendor Y suspended and Vendor Z pending, a signed-out visitor sees one vendor and one product, the shirt. Buyer A still sees all 3 lines of her own orders, including Vendor Y's scarves, because order history does not depend on a vendor's status, but her attempt to order Vendor Y's belt failed with "product ... is not for sale", and so did an attempt to order the pending vendor's lamp. Vendor Y still sees its own products and could still ship its paid belt. The applicant sees her lamp, which no shopper can. When the admin set Vendor Y back to active, its products returned to the storefront.

Allowed writes need the same care. Supabase's guide warns that "Matching no rows is not proof on its own", so check the row count and then read the data back as someone else. When Vendor X marked every line of order 1 shipped, the update reported 1 row, and reading as postgres afterwards showed Vendor Y's scarves still at to_ship. Twenty write attempts were run in all. The ones that should fail failed with the errors shown in the comments above; a buyer creating her own order, a vendor repricing its own product and an admin approving Vendor Z succeeded; and Vendor X repricing a Vendor Y product changed 0 rows.

To stop these checks regressing, turn them into tests. As of November 2026, Supabase's testing page says "All sql files use pgTAP as the test runner"; the files live in ./supabase/tests/database and run with supabase test db. Supabase's RLS guide adds: "Never prove an allowed write with lives_ok. It passes when the write matched zero rows." Assert on counts, and on the data that changed.

Performance: indexes, set-based helpers and the advisors

Marketplace policies run on every read of the busiest tables, so their cost shows as soon as order_items grows. Three habits keep it down. Index every column a policy filters on: orders.buyer_id, order_items.vendor_id and order_id, products.vendor_id and vendor_members.vendor_id. Supabase notes that a column only counts as indexed for this when it leads a btree index, which is why vendor_members puts user_id first in its primary key. Wrap auth.uid() and argument-free helpers in a select so they run once per query. And prefer a set-returning helper to one that takes a column from the row.

To see the difference, we loaded 200,004 order lines from just over 500 vendors into the local test database and ran select count(*) from order_items as Vendor X, who owns 1,998 of them, under three versions of the SELECT policy. These timings come from one laptop running PostgreSQL 18.3, not from Supabase, so the ratios are the point, not the milliseconds. Read your own plans the same way, as the user the app runs as.

Read the query plan as a signed-in vendorSQL
-- Read the plan as the user the app runs as.
begin;
set local role authenticated;
set local request.jwt.claim.sub = '00000000-0000-0000-0000-0000000000c3';
explain (analyze, costs off)
select count(*) from public.order_items;
rollback;
select count(*) from order_items as Vendor X: 200,004 lines on local PostgreSQL 18.3, range across runs
Policy versionExecution timeWhat the plan shows
vendor_id in (select private.my_vendor_ids()), helpers wrapped (this guide)13.2 to 15.6 msEach helper runs once; every line is checked against a hashed list of the caller's vendor ids
private.is_vendor_member(vendor_id), admin check wrapped712 to 731 msThe function runs once for each of the 200,004 lines
Per-row helpers with nothing wrapped, and the buyer check as exists() with a bare auth.uid()1,413 to 1,433 msTwo function calls per line, plus a sequential scan of orders
This guide's policy, with the app also filtering by vendor_id0.32 to 0.45 msAn index scan on order_items.vendor_id reads only Vendor X's lines

The last row is the cheapest fix of all: when the app asks for one vendor's lines, say so in the query as well as in the policy, for example with .eq('vendor_id', vendorId) in supabase-js. Supabase's RLS performance guide makes the same recommendation, because the filter lets Postgres use the index instead of testing every line against the policy.

The vendor-status check on products costs little. Postgres turns the EXISTS into one hashed read of the active vendors per query rather than a lookup per product. Counting all 20,204 products as a signed-out visitor took 2.7 to 3.1 ms with the check and about 1.5 ms without it, and an extra index on vendors (id, status) made no difference.

Security and production checks before launch

A schema that passes the tests above still needs a few things around it before real vendors and real money arrive.

  • Keep every policy, grant and trigger in migrations, so a staging project and production cannot drift apart. Supabase recommends keeping RLS changes in migrations.
  • Lock the basket when checkout starts. Server code should read the total from order_items, which the database priced, and move the order out of pending_payment before taking payment, so no line can be added under a payment already in progress.
  • Mark orders paid only from a verified payment webhook running with the secret key, never from a redirect page in the browser. Paying vendors out is covered on Stripe Connect marketplace payments.
  • Decrement stock in the database, in the transaction that confirms the order, with an update that fails when stock is too low. Reading stock in application code and writing it back oversells.
  • Give product images storage policies too. Supabase Storage uses RLS on storage.objects, and a public bucket serves files to anyone with the URL; see the storage buckets check in the checklist.
  • Decide what happens to orders when an account is deleted. orders.buyer_id has no on delete cascade here, so deleting a buyer who has orders fails until you decide whether to keep or anonymise those records.
  • Re-run the persona tests after every schema change, and after any AI tool edits a policy.
Supabase advisor checks that matter most for a marketplace (Database Advisors page, read 30 November 2026)
CheckLevelWhat it means here
0013_rls_disabled_in_publicERRORA table such as order_items has RLS off
0015_rls_references_user_metadataERRORA policy trusts a role the user can edit
0010_security_definer_viewERRORA vendor or admin view runs with its owner's rights
0024_permissive_rls_policyWARNA policy is always true, such as using (true) on orders
0028 and 0029, security definer function executableWARNA helper sits in an exposed schema and can be called as an RPC
0011_function_search_path_mutableWARNA function has no fixed search_path
0003_auth_rls_initplanWARNauth.uid() or a helper is evaluated once per row
0006_multiple_permissive_policiesWARNSeveral permissive policies for one role and command
0001_unindexed_foreign_keysINFOA foreign key such as order_items.order_id has no index

Run them from the dashboard's Advisors pages, with supabase db advisors in the CLI, or through the Supabase MCP server's get_advisors tool. Some findings may be intentional, so check each one against the access table at the top of this guide before changing anything.

When a targeted fix is enough, and when the schema must change

Many marketplaces need policy fixes, not a rebuild. The test is whether ownership is already in the data. If every order line can be traced to a vendor through a column, and roles already live somewhere the user cannot write, the fix is grants, policies, a helper or two, indexes and tests, and it can often ship without touching the app's screens.

The schema has to change when the data cannot answer the question a policy asks.

Targeted fix or schema change
What you findTargeted fixSchema change
Policies without TO, unwrapped auth.uid(), no indexesRewrite the policies and add the indexesNot needed
Vendor approval stored but never checkedAdd the vendor status check to the product policies and the pricing triggerNot needed
A vendor policy with no vendor conditionAdd the condition, if order lines already carry vendor_idAdd vendor_id to order lines and backfill it from products
Role in user_metadata or an editable profiles.rolePoint policies at a helper that reads a protected table or app_metadataAdd an admins table, and a vendor membership table if vendors are single users today
Address, totals and payment status all on ordersNone: no policy can show a vendor only the addressMove the address into its own table
One vendor per order, but baskets must now span vendorsNoneAdd order lines with their own vendor and a fulfilment status per line
Prices, totals or payout details written by the browserColumn grants and a pricing triggerMove checkout and payouts to server code if the client creates payments
Admin screens use the secret key in the browserRotate the key at onceRebuild admin access on the admin's own session plus server functions

If you can't tell which side your app is on, the Vibe Code Audit reads the schema, policies and payment flow of an existing app and gives each part a keep, harden or rebuild verdict. It costs $400, credited to the fix if you go ahead, and the report is an engineering review, not a security certification. The data exposed section of that page covers what the review looks at.

Building a marketplace, or not sure yours holds up?

DevoraX is two people, Sameem Amjad and Usman. A new marketplace build puts vendor rules like these in the database, with a buyer storefront, a vendor portal and an admin console over one backend, at a fixed price agreed in writing before work starts.

For a marketplace that already exists, start with the Vibe Code Audit: $400, credited to the fix if you go ahead. It reads the schema, the policies and the payment flow, and says what to keep, harden or rebuild.

Multi-Vendor Marketplace Development

What this guide does not cover

  • Stripe Connect itself: creating connected accounts, splitting payments and paying vendors out. See Stripe Connect marketplace payments.
  • Stock reservation and concurrency at checkout, which are mentioned here but not built.
  • Storage policies for product images, and Realtime subscriptions.
  • Roles inside a vendor team, such as staff who can ship but not change prices. The role column on vendor_members is where they would start.
  • A live Supabase project. Every snippet was tested on PostgreSQL 18.3 with Supabase's roles and auth.uid() recreated locally, so test on a branch or a local Supabase before production.
  • Predicting your project's speed. The timings come from one local machine and are there to compare policy shapes.

Sources

Platform documentation changes. Each source shows the date it was read for this guide.

  1. Supabase: Row Level Security · read 30 Nov 2026
  2. Supabase: Column Level Security · read 30 Nov 2026
  3. Supabase: Database Advisors · read 30 Nov 2026
  4. Supabase: RLS performance and best practices · read 30 Nov 2026
  5. Supabase: Testing your database · read 30 Nov 2026
  6. Supabase: API keys · read 30 Nov 2026
  7. Supabase: Storage access control · read 30 Nov 2026
  8. Supabase discussion #45329: tables not exposed to the Data API automatically · read 30 Nov 2026
  9. PostgreSQL: Row Security Policies · read 30 Nov 2026
  10. PostgreSQL: CREATE VIEW (security_invoker) · read 30 Nov 2026

Start with a free 30-minute call

Tell us where the app is stuck and what has to happen by when. We tell you whether an audit makes sense.

Book your free call