Skip to content
·9 min read

Supabase From Scratch for Auth, Database, and File Storage

How to set up Supabase as your complete backend when building with AI coding tools

Share

Supabase can provide authentication, a Postgres database and file storage. Connect those pieces through the signed-in user's identity, then test that another account cannot read or modify their data. Creating a login screen alone does not protect a table or a file.

This guide builds a private profile with a private avatar. Run the example in a disposable project before adapting it. In the November 7 local test, two disposable accounts confirmed their email addresses. The test also covered saving and reading a profile, blocking access by the other account, uploading a private avatar and downloading it through a signed link. Check hosted delivery and where your app’s confirmation links return separately.

Create a project and choose the right key

Use a disposable copy of your app and its own Supabase project for sign-in, the database and file storage. Before signing up or creating a table or bucket, compare the project URL in your test app’s settings with the URL of the test project you chose.

  • Local test for two disposable accounts. Follow the Supabase CLI setup to initialize a fresh local project for the test copy. Keep the default Mailpit settings. Before starting, confirm that the new configuration has no custom SMTP connection or Send Email Hook enabled. In the test copy’s supabase/config.toml, set site_url under [auth] to the address where your test app runs. Set enable_confirmations = true under [auth.email]. Start or restart the local project, then run supabase status to find its project URL, publishable key, Studio address and Mailpit address. Studio is the local dashboard for the steps below. Mailpit is a test inbox on your computer. It catches both confirmation messages without sending them out.
  • Hosted test. Use the project URL and publishable key from a separate test project. Keep Confirm email enabled and set the Site URL in Auth’s URL Configuration to the address of your test app. The built-in email service only delivers to addresses already on your Supabase organization’s team. It also limits the whole project to two Auth emails per hour. This exercise needs both sends, and a recent password reset or resend uses the same allowance. Use this route only if you control two eligible inboxes and the project can send both messages. If the allowance is partly used or you aren’t sure, wait for it to recover or use Mailpit. For other addresses, configure custom SMTP on the test project with your provider’s verified test sender. Before signup, confirm in the email service that the test sender captures messages or restricts delivery to your own test inboxes. Use Mailpit if you can’t verify the restriction.

Current API key guidance distinguishes publishable keys from secret keys. Legacy projects may still expose anon and service_role keys.

A browser may use a publishable key with correctly configured authorization. Secret and service-role keys must stay out of browser code and public assets. They can bypass the policies you are trying to test.

For a browser application, install the client:

npm install @supabase/supabase-js
import { createClient } from '@supabase/supabase-js';

// Public browser configuration, not a secret or service-role key.
const supabase = createClient(projectUrl, publishableKey);

How projectUrl and publishableKey reach the browser depends on your build system. Add them through its documented public configuration. If you use server-rendered Next.js auth, follow the current SSR client guide instead of assuming a browser-only session also authenticates a server request.

Sign up and wait for an authenticated session

Use two disposable email addresses. Open the test app in two separate browser profiles, one for account A and one for account B. Enable email/password sign-in for the test project if needed.

async function signUp(email: string, password: string) {
  const { data, error } = await supabase.auth.signUp({ email, password });
  if (error) throw error;
  // Confirmation can be required. A user object is not proof of a session.
  return data.session ? 'signed-in' : 'check-email';
}

async function signIn(email: string, password: string) {
  const { error } = await supabase.auth.signInWithPassword({ email, password });
  if (error) throw error;
  const { data, error: userError } = await supabase.auth.getUser();
  if (userError || !data.user) throw new Error('Sign in again');
  return data.user;
}

Use these functions behind your app’s forms. If signup is waiting for confirmation, tell the user to check their email. When something fails, show a plain-language explanation and a useful next action.

  1. In A’s browser profile, sign up and check that the app asks you to confirm your email. Find A’s message in Mailpit or your approved test inbox. Open the confirmation link in A’s browser profile. Check that it brings you back to the test app, then sign in if asked.
  2. Repeat in B’s browser profile with B’s message. Verify each browser is signed in as the intended account.
  3. If a message never arrives or a link opens the wrong app, check the project URL, test inbox and Site URL before continuing. Wait until both sign-ins work separately before creating profiles. The database policy needs a valid signed-in session.

The signup flow above does not implement OAuth or password reset.

Create a table with explicit permissions

Run this migration once in a fresh test project:

create table public.profiles (
  id uuid primary key references auth.users(id) on delete cascade,
  display_name text not null check (char_length(display_name) between 1 and 80),
  avatar_path text,
  created_at timestamptz not null default now()
);

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

create policy profiles_read_own on public.profiles
  for select to authenticated using ((select auth.uid()) = id);
create policy profiles_insert_own on public.profiles
  for insert to authenticated with check ((select auth.uid()) = id);
create policy profiles_update_own on public.profiles
  for update to authenticated
  using ((select auth.uid()) = id)
  with check ((select auth.uid()) = id);

This example deliberately provides no browser delete permission. USING restricts existing rows and WITH CHECK restricts new row values. Check the RLS reference before extending the policy to shared teams or roles.

Grants decide which operations a signed-in account can use. The row policies decide which profiles those operations can reach.

Save and read the signed-in user's profile

async function saveProfile(displayName: string) {
  const { data: auth, error: authError } = await supabase.auth.getUser();
  if (authError || !auth.user) throw new Error('Sign in again');
  const { data, error } = await supabase.from('profiles')
    .upsert({ id: auth.user.id, display_name: displayName })
    .select('id, display_name, avatar_path').single();
  if (error) throw error;
  return data;
}

async function readOwnProfile() {
  const { data, error } = await supabase.from('profiles')
    .select('id, display_name, avatar_path').maybeSingle();
  if (error) throw error;
  return data; // null means no visible profile yet, not a failed request.
}

The policy protects the query even without a client-side owner filter. A filter can narrow a request; it cannot substitute for server-enforced ownership.

Add a private avatar bucket

Create an avatars bucket in the dashboard with public access disabled. Configure allowed content types and an appropriate file-size limit for your app. Then add separate read and insert policies:

create policy avatars_read_own on storage.objects
  for select to authenticated
  using (bucket_id = 'avatars'
    and (storage.foldername(name))[1] = (select auth.uid())::text);

create policy avatars_insert_own on storage.objects
  for insert to authenticated
  with check (bucket_id = 'avatars'
    and (storage.foldername(name))[1] = (select auth.uid())::text);

The storage access-control guide explains the extra permissions needed for overwrites and other operations. This version uses a unique name and disables upsert, so it does not need an update policy.

async function uploadAvatar(file: File) {
  const { data: auth, error: authError } = await supabase.auth.getUser();
  if (authError || !auth.user) throw new Error('Sign in again');
  const path = `${auth.user.id}/${crypto.randomUUID()}`;
  const { error: uploadError } = await supabase.storage.from('avatars')
    .upload(path, file, { upsert: false });
  if (uploadError) throw uploadError;
  const { data, error: profileError } = await supabase.from('profiles')
    .update({ avatar_path: path }).eq('id', auth.user.id).select('id').single();
  if (profileError) throw profileError;
  return { path, profileId: data.id };
}

async function avatarUrl(path: string) {
  const { data, error } = await supabase.storage.from('avatars')
    .createSignedUrl(path, 60);
  if (error) throw error;
  return data.signedUrl;
}

Call saveProfile first. File upload and profile update are separate operations: if the update fails, the file can remain as an orphan requiring a controlled cleanup process. A private bucket does not become readable through getPublicUrl; use an authorized download or short-lived signed URL. Anyone who holds the signed link may be able to open the file. With Smart CDN, a stored response for that exact link can still be served after the 60-second token expires. Keep signed links out of logs and public messages. If future requests must stop when access ends, use an authorized download that checks the signed-in user’s current permission on each request. Send the protected response with Cache-Control: no-store to tell browsers and shared caches not to save it. Someone who already saved a copy can keep it.

Run the second-user test

Operation in a disposable projectExpected result
A saves and reads A's profileOwn record is returned
B reads by A's exact IDEmpty result, not A's private row
B updates A's profile with a returning selectNo returned row; A's stored values remain unchanged
B inserts a profile whose ID is A'sRejected
B uploads beneath A's avatar folderRejected
B tries to sign or download A's private pathDenied
Signed-out client reads profilesDenied by grants or receives no private data

Run the requests with each account's normal session and the publishable key. SQL-editor and service-role tests can bypass RLS and give misleading results. Verify stored state after denied writes, not just a status label in the UI.

Before using this pattern with real customer data, make sure your app has backups, upload limits, monitoring and a recovery plan.

PJ
Pranay Joshi

20+ years building products at scale. VP of Product & Engineering, startup founder, and AI coach. Helping dreamers turn ideas into reality with vibe coding.