specific build playbooksby updated 8 min read

Supabase RLS for AI Access to PHI Under HIPAA

When a health app sends patient data to an AI model, the database should decide which rows each user can read. Supabase Row Level Security policies, a narrow view for the AI code, an access log, and the BAAs to have in place first.

Give every patient record a care-team assignment, write Supabase Row Level Security policies that return only assigned patients' rows, expose a narrow view to the AI code, and call the model from server code that queries under the signed-in user's token. Supabase signs a BAA on the Team plan or above with its HIPAA add-on.

When a healthcare app sends patient notes to an AI model, the safest place to decide what a user may read is the database itself. Supabase's Row Level Security (RLS) docs describe a policy as a WHERE clause added to every query on a table. If the server code that calls the model queries as the signed-in user, the model can only ever receive rows that user was allowed to see.

This is a build pattern, not legal advice. Have privacy counsel review the design before PHI goes into it.

What HIPAA asks of the access layer

Three parts of the HIPAA rules shape this design:

  • Access control: 45 CFR 164.312(a)(1) requires technical policies and procedures that allow access to electronic PHI only to the persons or software programs granted access rights. Paragraph (a)(2)(i) requires a unique name or number for identifying and tracking each user.
  • Audit controls: section 164.312(b) requires mechanisms "that record and examine activity in information systems" that contain or use electronic PHI.
  • Minimum necessary: section 164.502(b) requires reasonable efforts to limit PHI to the minimum necessary for the purpose of a use, disclosure or request. Disclosures to or requests by a health care provider for treatment are exempt. Section 164.514(d)(2) asks a covered entity to identify which classes of its workforce need access to PHI, and which categories of PHI each class needs.

In this build, a care-team table records who may see which patient, RLS policies decide which tables each role can read, and an access log records each disclosure to the AI service.

Before PHI goes into Supabase

Supabase's shared responsibility model says you sign a Business Associate Agreement with Supabase, and that you need to be at least on the Team plan to sign one. HIPAA is a paid add-on on the Team and Enterprise plans, and Supabase's pricing page lists the Team plan from $599 a month (as listed on December 2, 2026). Supabase also lists your side of the setup:

  • Mark the projects that hold PHI as HIPAA projects. Supabase then runs extra checks and shows warnings in the Security Advisor.
  • Turn on Point in Time Recovery, SSL Enforcement and Network Restrictions, and keep Postgres connection logging on.
  • Require MFA on every account in the Supabase organization.
  • Keep PHI out of public Storage buckets.

Step 1: Care-team assignments

-- Who is on whose care team, with history kept.
create table public.care_assignments (
  id uuid primary key default gen_random_uuid(),
  patient_id uuid not null references public.patients (id),
  user_id uuid not null references auth.users (id),
  role text not null check (role in ('clinician', 'nurse', 'billing')),
  starts_at timestamptz not null default now(),
  ends_at timestamptz
);

-- The policy filters on user_id, so it leads the index.
create index care_assignments_active_idx
  on public.care_assignments (user_id, patient_id)
  where ends_at is null;

-- Runs as its owner so policies can read assignments without recursion.
-- Kept in a schema the Data API doesn't expose.
create schema if not exists private;

create function private.assigned_patient_ids(allowed_roles text[])
returns setof uuid
language sql
security definer
set search_path = ''
stable
as $$
  select patient_id
  from public.care_assignments
  where user_id = (select auth.uid())
    and role = any (allowed_roles)
    and ends_at is null
$$;

revoke execute on function private.assigned_patient_ids(text[]) from public;
grant usage on schema private to authenticated;
grant execute on function private.assigned_patient_ids(text[]) to authenticated;

The function is security definer, so it runs as its owner and can read assignments without tripping over the policies on that table. Supabase's docs recommend this pattern when a policy needs to read another table, with search_path set to an empty string and the function kept in a schema the API doesn't expose. They also recommend wrapping auth.uid() in a select, naming the role with to authenticated, and indexing every column a policy filters on, with that column first in the index.

Step 2: Policies by role, and a narrow view for the AI

alter table public.clinical_notes enable row level security;

create policy "care team reads notes"
  on public.clinical_notes for select
  to authenticated
  using (patient_id in (select private.assigned_patient_ids(array['clinician', 'nurse'])));

create index clinical_notes_patient_idx on public.clinical_notes (patient_id);

alter table public.billing_lines enable row level security;

create policy "billing staff read billing lines"
  on public.billing_lines for select
  to authenticated
  using (patient_id in (select private.assigned_patient_ids(array['billing'])));

create index billing_lines_patient_idx on public.billing_lines (patient_id);

-- Only the columns a summary needs. security_invoker makes the view obey
-- the policies on clinical_notes instead of bypassing them.
create view public.ai_note_context
with (security_invoker = true)
as select patient_id, note_date, note_type, body
from public.clinical_notes;

Billing data sits in its own table with its own policy, so billing staff never get a policy on clinical notes. Supabase does support column-level privileges, but its docs call them an advanced feature and recommend RLS with dedicated tables for most cases.

The view matters as much as the policies. Supabase's docs warn that views bypass RLS by default because they're usually created by the postgres user. In Postgres 15 and above, security_invoker = true makes the view obey the policies on the tables underneath. The view also limits what the AI code can select: the note fields, without the name, birth date or record number that live in the patients table. The note text can still contain identifiers, so treat everything the view returns as PHI.

Step 3: An access log users can write but not change

create table public.phi_access_log (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users (id),
  patient_id uuid not null references public.patients (id),
  action text not null,   -- 'view', 'ai_summary', 'export'
  vendor text,            -- set when data goes to an outside service
  request_id text,
  created_at timestamptz not null default now()
);

alter table public.phi_access_log enable row level security;
revoke all on public.phi_access_log from anon, authenticated;
grant insert on public.phi_access_log to authenticated;

create policy "users record their own access"
  on public.phi_access_log for insert
  to authenticated
  with check (user_id = (select auth.uid()));

Signed-in users can add a row for their own user ID, and that's all. They have no grant to read, update or delete the log, so reviewing it is a job for an administrator connecting with elevated access. Supabase's insert reference notes that inserted rows aren't returned unless you chain .select(), which matters here because users can't read the table back.

Step 4: Call the model as the user

import Anthropic from "@anthropic-ai/sdk";
import { createClient } from "@supabase/supabase-js";

const anthropic = new Anthropic(); // API key from an organization covered by your BAA

export async function summarizeRecentNotes(accessToken: string, patientId: string) {
  // Publishable key plus the signed-in user's token: every query runs under RLS as that user.
  const supabase = createClient(process.env.SUPABASE_URL!, process.env.SUPABASE_PUBLISHABLE_KEY!, {
    global: { headers: { Authorization: `Bearer ${accessToken}` } },
    auth: { persistSession: false },
  });

  const { data: userData, error: userError } = await supabase.auth.getUser(accessToken);
  if (userError || !userData.user) throw new Error("not signed in");

  const since = new Date(Date.now() - 180 * 24 * 60 * 60 * 1000).toISOString();
  const { data: notes, error } = await supabase
    .from("ai_note_context")
    .select("note_date, note_type, body")
    .eq("patient_id", patientId)
    .gte("note_date", since)
    .order("note_date", { ascending: false });
  if (error) throw error;
  if (!notes || notes.length === 0) return null; // no assignment or no recent notes: nothing leaves

  const requestId = crypto.randomUUID();
  const { error: logError } = await supabase.from("phi_access_log").insert({
    user_id: userData.user.id,
    patient_id: patientId,
    action: "ai_summary",
    vendor: "anthropic",
    request_id: requestId,
  });
  if (logError) throw logError; // no log row, no disclosure

  const response = await anthropic.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 16000,
    system: "Summarize these notes for the treating clinician. Use only the notes given and cite each note's date.",
    messages: [{ role: "user", content: JSON.stringify(notes) }],
  });

  return response.content.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("\n");
}

Supabase's API keys guide says the publishable key only reaches what RLS allows, and the secret key bypasses RLS. Its RLS docs add that a secret key bypasses RLS only when the request carries no user access token. Using the publishable key with the user's token in this code path means a mistake in the code still can't read past the policies. If the user isn't on the patient's care team, the query returns no rows, and the function returns before anything is logged or sent. The legacy anon and service_role keys are being deprecated in early 2027, so new code should use the publishable and secret keys.

The log row is written before the request goes out, and a failed insert stops the request.

The AI vendor needs a BAA too

The model provider receives PHI, so it needs its own BAA. Anthropic's help center, updated October 30, 2026, says Anthropic provides a BAA covering its HIPAA-ready services, such as its first-party API, signed by the organization's Primary Owner. The same article lists API features that aren't covered and aren't available to HIPAA-ready API users, including the Batch API, the Files API, the Skills API, code execution and web fetch, and it says Messages API features that aren't listed aren't covered. Check the current list before you add a feature to this code path.

Test the policies

Supabase's RLS docs recommend pgTAP tests under supabase/tests/, created with supabase test new and run with supabase test db, with cases for both members and non-members. For this design, test at least these:

  • A clinician assigned to a patient reads that patient's notes through the view.
  • A clinician whose assignment has ended reads nothing.
  • A billing user reads billing lines and no clinical notes.
  • A user can add a log row for their own ID, but not for someone else's, and can't read or delete any rows.

What tends to break

  • A secret key in the AI path: it skips every policy above. Keep secret keys for administrative jobs that never touch the summary code.
  • A new table without RLS: enable RLS and write the policies in the same migration that creates the table.
  • A view without security_invoker: it returns every row the policies were meant to withhold.
  • Slow policies on large tables: the index on user_id and the select-wrapped auth.uid() keep the check from running once per row.

RLS is one technical control. Your BAAs, risk assessment, policies and workforce training sit outside the database. For how to compare Postgres hosts in the first place, see Supabase vs Neon vs Turso.

Sources

  1. Supabase docs, Row Level Security (policies, security definer functions, indexes, views and security_invoker, bypassing RLS) (checked 2026-12-02)
  2. Supabase docs, API keys (publishable and secret keys, legacy anon and service_role keys deprecated in early 2027) (checked 2026-12-02)
  3. Supabase docs, Shared responsibility model: healthcare data (BAA on Team plan or above, HIPAA project settings) (checked 2026-12-02)
  4. Supabase docs, HIPAA projects (HIPAA add-on, Security Advisor checks) (checked 2026-12-02)
  5. Supabase pricing (Team plan, HIPAA available as a paid add-on) (checked 2026-12-02)
  6. Supabase docs, Column Level Security (checked 2026-12-02)
  7. 45 CFR 164.502(b), minimum necessary standard and its exceptions (LII) (checked 2026-12-02)
  8. 45 CFR 164.514(d)(2), minimum necessary uses: workforce classes and categories of PHI (LII) (checked 2026-12-02)
  9. 45 CFR 164.312, HIPAA Security Rule technical safeguards: access control and audit controls (LII) (checked 2026-12-02)
  10. Anthropic Help Center, Business Associate Agreements (BAA) for commercial customers (Oct. 30, 2026) (checked 2026-12-02)
supabaserlshipaaphilong-tail
go deeper

Worked steps, FAQs and resources on this topic.

read the guide
the list

Get the next one.

Field notes from real deployments, written the way this one was. No schedule promised and nothing sold to you. Unsubscribe whenever.

ready to ship?

Let's build yours.

Reading is the easy part. We do the work. Tell us what's broken and we'll tell you straight up whether we can help.

let's talk