Skip to content
← All guides

Security

Supabase Storage bucket is public: how to make user files private without breaking the app

By Jan Lipmann, appienceChecked against sources on 10 min read

A public Supabase bucket skips access control for downloads: anyone who has a file's URL can open it, no account needed. Making it private is one switch, but if you flip it first, every image and download link in your app breaks at once. The safe order: write policies, then move existing files into per-user folders and change the app to signed URLs together, and only then switch the bucket to private.

SupabaseSupabase StoragePostgreSQL

What you are seeing

Supabase has two kinds of bucket. In a private bucket every operation, downloads included, goes through your access policies. A public bucket "effectively bypasses access controls" for reading files, so anyone who has the URL can open the file (Storage Buckets). Signs that private files ended up in a public bucket:

  • File links in your app look like https://YOUR-PROJECT-REF.supabase.co/storage/v1/object/public/BUCKET/... - the /object/public/ part is the URL format of public buckets (Serving assets).
  • You paste a file link into a private browser window, where you are not signed in, and the invoice, ID scan or photo opens.
  • A customer tells you they opened someone else's file, for example by changing a number or name in a link.
  • Supabase's Security Advisor shows lint 0025 (public_bucket_allows_listing, "Public Bucket Allows Listing"): a public bucket also has a broad read policy, so its file list can be fetched through the API, not just files whose URL someone knows (lint 0025).
  • The code your AI tool wrote calls getPublicUrl(...) for uploads such as documents, receipts or chat attachments.
Note: A public bucket is not wrong in itself. Supabase lists profile pictures, public media and blog images as typical uses, and public buckets are faster because the CDN can cache them for everyone (Storage Buckets). The problem is private files in a public bucket.

How to check it yourself

Run these against your own project only. All queries below only read data, and the role tests run inside a transaction that is rolled back. Everything happens in the Supabase dashboard, in SQL Editor. Supabase asks you to treat the storage tables as read-only in SQL and to change files only through the Storage API (Storage schema) - reading them is fine.

1. Which buckets are public

select id, public, file_size_limit, allowed_mime_types, created_at
from storage.buckets
order by public desc, id;
public = true means anyone with a file URL can download from that bucket. New buckets are private unless someone chose otherwise (Storage Buckets).

2. What is inside the public buckets

select bucket_id, name, storage.extension(name) as extension, created_at
from storage.objects
where bucket_id in (select id from storage.buckets where public)
order by created_at desc
limit 100;
Read the file names and extensions. PDFs, documents, scans, photos of people, voice notes or chat attachments are private by nature. storage.extension() is one of Supabase's storage helper functions (Helper functions).

Also look at how files are named. A path like invoices/1043.pdf or one that contains a user's email can be guessed; a path with a random id is harder to guess but still opens for anyone the link reaches - a forwarded email, a screenshot, browser history, a log.

3. Which storage policies exist

select policyname, permissive, cmd, roles, qual, with_check
from pg_policies
where schemaname = 'storage'
  and tablename = 'objects'
order by cmd, policyname;
qual is the condition for reading, updating and deleting; with_check is the condition for new or changed files. Uploads need an insert policy, overwriting with upsert also needs select and update (Storage Access Control).

What to look for in the result:

  • A SELECT or ALL policy whose condition is only true or only bucket_id = 'some_bucket'. On a public bucket this is what lint 0025 flags: it lets clients list every file, and public files do not need it to be downloaded (lint 0025 source).
  • The same kind of broad select policy on a private bucket. It means every role it names (authenticated = every signed-in user) can download every file in the bucket and create signed links to them, because both need only select permission (createSignedUrl).
  • Policies that compare the folder or owner with the user, such as (storage.foldername(name))[1] = (select auth.jwt()->>'sub') or owner_id = (select auth.uid()::text). That is the pattern you want (Storage Access Control, Ownership).
  • No policies at all: files can still be downloaded from a public bucket by URL, but uploads from the app should fail - unless the app uploads with a secret or service_role key, which bypasses policies entirely. That is a separate problem, see our guide to a leaked service_role key.

4. What a visitor and a signed-in user can list

Listing files through the API needs select permission on storage.objects (list), so counting rows as each role shows what that role can enumerate. Supabase's docs describe switching role and identity this way to test policies (Row Level Security). First, as a visitor who is not signed in:

begin;
set local role anon;

select bucket_id, count(*) as files_visible
from storage.objects
group by bucket_id;

rollback;

Then as one of your own test accounts (find its id under Authentication > Users). Paste the id in both places:

begin;
set local role authenticated;
set local request.jwt.claims = '{"sub": "TEST-USER-UUID", "role": "authenticated"}';

select bucket_id,
       count(*) as files_visible,
       count(*) filter (
         where (storage.foldername(name))[1] is distinct from 'TEST-USER-UUID'
       ) as files_outside_own_folder
from storage.objects
group by bucket_id;

rollback;
For a bucket with private files, files_outside_own_folder should be 0 (if your app uses one folder per user). The test sets request.jwt.claims rather than only request.jwt.claim.sub, because policies written with auth.jwt()->>'sub' read the full claims. SQL Editor may show only the result of the last statement: select the lines from begin; through the select, run only that, read the counts, then run rollback;. Policies that use storage.allow_only_operation() or storage.allow_any_operation() depend on which Storage API call is running, and in SQL Editor none is, so treat this test as approximate for them (Helper functions).

5. Where the app relies on public URLs

Before you change anything, find every place that will break. In the app's code (in a terminal, in the project folder):

grep -rn "getPublicUrl\|/storage/v1/object/public/" --include="*.ts" --include="*.tsx" --include="*.js" --include="*.jsx" . | grep -v node_modules

And in the database: columns that may hold full file URLs instead of file paths. Saved public URLs stop working once the bucket is private:

select table_name, column_name, data_type
from information_schema.columns
where table_schema = 'public'
  and (column_name ilike '%url%' or column_name ilike '%path%'
       or column_name ilike '%file%' or column_name ilike '%image%'
       or column_name ilike '%avatar%' or column_name ilike '%photo%')
order by table_name, column_name;
Then look at a few values in each column: select avatar_url from public.profiles limit 5; (with your table and column names).

Why it happens

"Public" on a Supabase bucket means one specific thing: anyone can download a file if they have its URL. Uploading, deleting, moving and listing still go through policies (Storage Buckets). That is why it is an easy setting to choose: it makes images show up with no extra code, and the app still seems protected because uploads need a policy.

  • Public URLs are the shortest way to show a file. getPublicUrl() returns a link without asking the server anything; it does not even check whether the bucket is public (getPublicUrl). A private bucket needs a signed URL or the user's token for every file, which means more code.
  • Generated code tends to fix the error in front of it. If a private file does not load, flipping the bucket to public or adding a broad read policy makes the screen work immediately.
  • One bucket for everything. Avatars, which are often fine to be public, and invoices, which are not, end up in the same uploads bucket, and the bucket gets the setting the avatars needed.
  • Full URLs saved in the database. Once https://.../object/public/... is stored in a column, making the bucket private breaks every saved link, so the setting stays.
  • Ownership is recorded but not enforced. Supabase stores who uploaded each file in owner_id, but says ownership by itself provides no access control - only a policy that checks it does (Ownership).

How to fix it

Warning: Do the steps in this order and test on a Supabase branch or a copy of the project first. Switching the bucket to private before the app uses signed URLs breaks every image and download at once. Steps 3 and 4 belong together: once the app uses signed URLs, old files that are not yet in a user folder will not open (see step 3). Moving files changes their paths; deleting files cannot be undone.

1. Decide what stays public

Go through the list from check 2 and sort files into two groups: things you would be fine to see on a public web page (product images, public profile pictures, blog images) and everything else. If both are mixed in one bucket, create a new private bucket for the private files rather than making the shared one private. In the dashboard: Storage, then New bucket, leaving it private (the default).

For buckets that stay public, remove broad read policies. Files still download by URL without them; only listing stops (lint 0025):

drop policy if exists "Public bucket listing" on storage.objects;
Use the exact policy name from check 3. Before dropping, make sure the app does not call list() on that bucket for anonymous visitors.

2. Write policies that keep each user in their own folder

Supabase's documented pattern stores each user's files in a folder named after their user id, USER-ID/file.pdf, and checks the first folder of the path in the policy (Storage Access Control). Replace documents with your bucket's id:

begin;

create policy "Users read their own documents"
on storage.objects for select
to authenticated
using (
  bucket_id = 'documents'
  and (storage.foldername(name))[1] = (select auth.jwt()->>'sub')
);

create policy "Users upload to their own folder"
on storage.objects for insert
to authenticated
with check (
  bucket_id = 'documents'
  and (storage.foldername(name))[1] = (select auth.jwt()->>'sub')
);

create policy "Users replace their own documents"
on storage.objects for update
to authenticated
using (
  bucket_id = 'documents'
  and (storage.foldername(name))[1] = (select auth.jwt()->>'sub')
)
with check (
  bucket_id = 'documents'
  and (storage.foldername(name))[1] = (select auth.jwt()->>'sub')
);

create policy "Users delete their own documents"
on storage.objects for delete
to authenticated
using (
  bucket_id = 'documents'
  and (storage.foldername(name))[1] = (select auth.jwt()->>'sub')
);

commit;
Leave out what users should never do - if they must not delete files, skip the delete policy. Uploading with upsert: true needs the select, insert and update policies together (upload).
  • Drop any broad policy on this bucket from check 3 (for example bucket_id = 'documents' with no user check). Postgres combines permissive policies with OR, so one broad policy cancels the careful ones next to it (PostgreSQL: CREATE POLICY). The same mistake on tables is covered in our guide to "to authenticated" policies.
  • Why the folder and not owner_id: files uploaded with a secret key or through the dashboard get no owner, and a moved file gets the owner of whoever moved it (Ownership, Copy and move). The path stays correct after the migration in step 4. If all your files were uploaded by the users themselves and you never move them, owner_id = (select auth.uid()::text) works too.
  • Shared files (a team's documents, a chat between two people) need a policy that checks membership in your own tables instead. That is where mistakes are easy - see when to get help below.

3. Change the app: upload to the user's folder, store the path, show files with signed URLs

Three changes in the code that handles files. You can give this section to your AI tool as the instruction. Uploading into the user's folder, with a random file name:

const { data: { user } } = await supabase.auth.getUser();
if (!user) throw new Error("Not signed in");

// Storage rejects keys with non-ASCII letters and some symbols, so clean the name.
const safeName = file.name
  .normalize("NFKD")
  .replace(/[\u0300-\u036f]/g, "")
  .replace(/[^\w.-]+/g, "_");
const path = `${user.id}/${crypto.randomUUID()}-${safeName}`;

const { error: uploadError } = await supabase.storage
  .from("documents")
  .upload(path, file);
if (uploadError) throw uploadError;

// Save the path, not a URL.
const { error: saveError } = await supabase
  .from("documents")
  .insert({ user_id: user.id, file_path: path });
if (saveError) throw saveError;
Supabase Storage accepts only letters A-Z, digits and a short list of symbols in object keys, so a file name like faktura-łódź.pdf would fail with an invalid key error (Storage key rules). If you want to show the original name, keep it in your table next to the path.

Showing or downloading a file with a signed URL, which works for a limited number of seconds and only if the user's select policy allows that file (createSignedUrl):

const { data, error } = await supabase.storage
  .from("documents")
  .createSignedUrl(row.file_path, 60 * 10); // valid for 10 minutes

if (error) throw error;
// Use data.signedUrl in <img src> or a download link.
For a list of files there is createSignedUrls([...paths], seconds), one request for all of them. Do not store signed URLs in the database - create them when the screen opens.
  • Replace every getPublicUrl call you found in check 5 for this bucket. A public URL for a private bucket does not download (Serving assets).
  • Until step 4 has moved the existing files, signed URLs for them will fail, because the new select policy only allows the user's own folder (createSignedUrl). Run the migration in step 4 right after deploying this change, or before it if your table already stores paths - while the bucket is still public, the old getPublicUrl code keeps working on the moved paths.
  • Keep expiry times short. Supabase cannot revoke a single signed URL: to cut one off you have to delete, move or rename the file, or rotate the project's URL signing key and then revoke the old one, which cuts off all of them. Rotating alone is not enough, because both keys are accepted until the old one is revoked, and responses already cached on the CDN can still be served until you purge the cache (Serving assets, URL signing keys). A signed URL valid for years is effectively a public link.
  • Each signed URL has its own token and its own CDN cache entry, so private files get fewer cache hits than public ones. Creating a new signed URL on every render means the cache never helps (Smart CDN). For images shown often, keep the signed URL for the life of the screen.

4. Move existing files into user folders

Files uploaded before step 3 are not in a user folder, so after the switch nobody can open them. If a table records which user each file belongs to, move them with a one-off script run on your own computer or in an Edge Function - never in the app, because it needs the secret key, which bypasses all storage policies (Storage Access Control). Files must be moved through the Storage API, not by editing storage.objects with SQL (Storage schema).

// One-off migration. Run as an ES module with Node, never ship it in the app.
import { createClient } from "@supabase/supabase-js";

const BUCKET = "documents";
const supabase = createClient(process.env.SUPABASE_URL!, process.env.SUPABASE_SECRET_KEY!, {
  auth: { persistSession: false },
});

const { data: rows, error } = await supabase
  .from("documents")
  .select("id, user_id, file_path")
  .range(0, 999);
if (error) throw error;

for (const row of rows) {
  if (row.file_path.startsWith(`${row.user_id}/`)) continue; // already moved

  const fileName = row.file_path.split("/").pop();
  const newPath = `${row.user_id}/${fileName}`;

  const { error: moveError } = await supabase.storage.from(BUCKET).move(row.file_path, newPath);
  if (moveError) {
    console.error("move failed", row.id, moveError.message);
    continue;
  }

  const { error: updateError } = await supabase
    .from("documents")
    .update({ file_path: newPath })
    .eq("id", row.id);
  if (updateError) console.error("path not saved", row.id, newPath, updateError.message);
}
Supabase returns at most 1,000 rows per request by default, so for more rows repeat with .range(1000, 1999) and so on (JavaScript reference). If your column holds full public URLs, turn them into paths first: the path is everything after /object/public/documents/. Keep the output - every "path not saved" line is a file that moved while the table still points to the old path.

5. Switch the bucket to private

Only now, with the app deployed and using signed URLs. In the dashboard: Storage, open the bucket's menu and edit the bucket so it is no longer public. From code, the JavaScript client has updateBucket(id, { public: false }) (updateBucket). The lint 0025 docs give the same change as SQL (lint 0025); it is the one documented exception to treating the storage tables as read-only:

update storage.buckets
set public = false
where id = 'documents';

6. Deal with copies that are already out there

  • Moving a file to a new path in step 4 already means its old public URL points at nothing.
  • Files are cached on Supabase's CDN. Supabase's docs do not say whether switching a bucket to private clears that cache. On Pro plans and above you can purge a whole bucket's CDN cache with the secret key; it takes up to 60 seconds and does not clear copies in users' browsers, which keep them until the file's cacheControl time runs out (Purge CDN cache).
  • Anyone who downloaded a file has it. Nothing in Supabase takes that back. If a file was sensitive and its URL could have reached people who should not have it, treat it as a possible data breach (see below).

Verify

Run checks 1 to 4 again: the bucket shows public = false, the anonymous count is 0 for it, and files_outside_own_folder is 0 for two different test accounts. Open an old public link in a private browser window - it should return an error instead of the file. Then use the app as a normal user: upload a file, see it, download it, and sign in as a second test user to confirm the first user's file does not show up.

When to get help

The folder-per-user pattern covers files that belong to exactly one person. Get a second pair of eyes when:

  • Files are shared - between members of a team, between a client and a provider, between two people in a chat. Those policies need a membership check against your own tables, and a wrong join quietly opens one company's files to another.
  • You cannot tell which user each existing file belongs to, so the migration in step 4 has nothing to go on.
  • The app is live and you need to switch without breaking images for current users, or it is a mobile app where old versions in the store still request public URLs.
  • The bucket held identity documents, medical or financial files and you do not know who saw the links. If you are subject to the GDPR, a personal data breach generally has to be reported to the supervisory authority within 72 hours of becoming aware of it, unless it is unlikely to result in a risk to people (GDPR, Article 33). Get legal advice on that part.
  • Uploads or downloads now fail with permission errors and you cannot tell which policy is missing.

Sources

Primary documentation this guide was checked against. Platforms change - if something here no longer matches, the source wins.

Frequently asked questions

If my file names are random, is a public bucket safe enough?
It is harder to guess a random name, but the file still opens for anyone the link reaches - through a forwarded message, a screenshot, browser history or a log. A public bucket also skips your policies for downloads entirely, so you cannot limit a file to its owner. For anything private, use a private bucket with signed URLs.
My bucket is private. Are my files safe?
Only as safe as its policies. A select policy like bucket_id = 'documents' for authenticated lets every signed-in user download every file and create signed links to them. Each user's policy has to check that the file is theirs, for example with (storage.foldername(name))[1] = (select auth.jwt()->>'sub').
Why did all my images break after I made the bucket private?
The app shows them with public URLs (/storage/v1/object/public/...), and those do not work for a private bucket. Switch the app to createSignedUrl or createSignedUrls and store file paths instead of URLs. If you need the app working right now, make the bucket public again, do the app change, then switch.
Can I revoke a signed URL I already handed out?
Not one by one. Supabase says to delete, move or rename the file, or to rotate and then revoke the project's URL signing key, which invalidates all signed URLs at once. With Smart CDN, a cached response can still be served for that exact URL until the cache entry expires, so for a hard cut-off delete the file or purge the cache.
Does the Supabase Security Advisor warn about public buckets?
Not about every public bucket. Lint 0025 warns only when a public bucket also has a broad read policy on storage.objects that makes its files listable. A public bucket full of invoices without such a policy is not flagged, so run check 2 yourself.

Related guides

Fixed-price audit

Want someone to check the whole app, not just this?

A review of data security, production readiness and App Store readiness for apps built with AI tools. 900 USD, a ranked list of fixes within 5 business days.