Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 31 ยท Storage and Functions

File Storage and Uploads

Upload and serve files with Cloud Storage for Firebase and Supabase Storage: buckets, public vs private, signed URLs, access rules, limits and resizing.

Databases are good at small structured values, not at photos, PDFs or videos. Both platforms therefore include object storage: a place to put files, give them a path, and hand out URLs. You get uploads from the browser, access control, and a global CDN without running your own file server.

This lesson covers Cloud Storage for Firebase and Supabase Storage: buckets, uploading and downloading, public and private files, signed URLs, rules for access, size and type checks, and resizing images. The SDK code is read-only because it needs a project. The runnable part is a stand-in bucket that signs expiring URLs with HMAC; real services use their own signing, but the idea is the same. Make sure you know Firestore Security Rules and Row Level Security Policies, because storage is protected by the same ideas.

Files live in buckets

Bucket A named container for files.
Path avatars/ana/photo.png is a key, not a real folder.
URL Public link, or a signed link that expires.
Access rules Decide who can read and write each path.

The database stores the path, the bucket stores the bytes.

1 / 2

Cloud Storage for Firebase

Firebase Storage sits on a Google Cloud Storage bucket created with your project. Files are addressed by a path inside it.

JavaScript
// Firebase (read-only)
import { getStorage, ref, uploadBytes, uploadBytesResumable, getDownloadURL, deleteObject } from "firebase/storage";

const storage = getStorage();
const fileRef = ref(storage, `avatars/${user.uid}/profile.png`);

// Simple upload with metadata
await uploadBytes(fileRef, file, { contentType: file.type });

// Resumable upload with progress
const task = uploadBytesResumable(fileRef, file);
task.on("state_changed", (snap) => {
  const percent = (snap.bytesTransferred / snap.totalBytes) * 100;
  console.log(Math.round(percent) + "%");
});

// A long-lived link containing a download token
const url = await getDownloadURL(fileRef);

await deleteObject(fileRef);

getDownloadURL returns a link with an unguessable token. Anyone who has the link can open the file, even if your storage rules would deny them. Treat it like a password in a URL: fine for avatars, not for private documents.

Access is decided by Storage Security Rules, which look like Firestore rules:

Text
// storage.rules (read-only)
rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /avatars/{userId}/{fileName} {
      allow read: if true;
      allow write: if request.auth != null
                   && request.auth.uid == userId
                   && request.resource.size < 2 * 1024 * 1024
                   && request.resource.contentType.matches('image/(png|jpeg|webp)');
    }
    match /private/{userId}/{allPaths=**} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}

The rules check the signed-in user, the size in bytes, and the content type of the upload. A file bigger than 2 MB, or a PDF pretending to be an avatar, is rejected before it is stored.

Supabase Storage

Supabase Storage keeps file metadata in a Postgres schema called storage, with the bytes in an S3-compatible store. That means access control uses RLS policies on storage.objects, written in SQL.

Buckets are either public (files readable by anyone who knows the URL) or private (every access needs authorization or a signed URL).

JavaScript
// Supabase (read-only)
const { data, error } = await supabase.storage
  .from("avatars")
  .upload(`${user.id}/profile.png`, file, {
    contentType: file.type,
    upsert: true,
  });

// Public bucket: build a stable URL
const { data: pub } = supabase.storage.from("avatars").getPublicUrl(`${user.id}/profile.png`);
console.log(pub.publicUrl);

// Private bucket: ask for a link that expires in 60 seconds
const { data: signed } = await supabase.storage
  .from("documents")
  .createSignedUrl(`${user.id}/contract.pdf`, 60);
console.log(signed.signedUrl);

await supabase.storage.from("avatars").remove([`${user.id}/profile.png`]);

The bucket's own settings can limit the allowed MIME types and the maximum file size, which gives you a first layer of checks. Policies decide who may touch which path:

SQL
-- read-only
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.uid())::text
  );

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.uid())::text
  );

The helper storage.foldername(name) splits the object name into folders, so the first folder acts as the owner id. This "one folder per user" layout is the simplest safe pattern in both platforms.

Public or private?

Public Private
Good for Avatars, product images, site assets Invoices, contracts, user uploads
Access Anyone with the URL Signed-in user with a matching rule, or signed URL
Caching Easy on the CDN Per-link, short lifetime
Risk Link sharing is unstoppable Forgotten policies or long expiry

Never put private files in a public bucket and rely on a hard-to-guess name. Names leak through logs, screenshots and shared links.

Signed URLs

A signed URL packs three things into a link: what it opens, until when, and a signature that proves your backend created it. The storage server recomputes the signature when the link is used. If the path or expiry was edited, the signature no longer matches and access is refused. After the expiry time the link stops working even when the signature is right.

Use short lifetimes (seconds or minutes) for downloads shown right away, and create the link only after your code has checked that the user may see the file.

Stand-in bucket with signed URLs

The Node stand-in below keeps files in memory and signs links with HMAC-SHA256 from node:crypto. A fake clock makes the output predictable. It shows the three outcomes: a valid link, an edited link and an expired link. Real services use their own formats, but the verification idea is the same. For more on signing, see OAuth Providers, Magic Links and JWTs.

Node.js Stand-in bucket with expiring signed URLs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The signature covers both the path and the expiry, so changing either makes it fail. The size and type checks run at upload time, the same two checks that rules and bucket settings give you.

Size and type checks, and resizing

Checks should exist on the server side, not only in the file picker. Use:

  • Storage rules (request.resource.size, contentType) or bucket limits for size and MIME type.
  • A function that runs when a file is created, to scan, rename or process it (see Cloud Functions and Edge Functions).
  • Remember that a content type is declared by the client; for high-risk uploads, inspect the actual bytes in a function.

Image resizing. Do not serve a 6 MB camera photo as a 64 px avatar. Supabase can transform images on the fly (a transform option with width, height and quality on getPublicUrl or createSignedUrl, available on paid plans). Firebase has an official "Resize Images" extension that creates thumbnails when a file is uploaded, and many teams use an image CDN in front instead. Resize on upload for predictable cost, or on demand for flexibility.

The second stand-in plans a thumbnail size while keeping the aspect ratio. It also shows why you request an image size close to what the page displays.

JS Choosing a thumbnail size

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A 64 px avatar needs under 0.1% of the original pixels. Serving the original would send hundreds of times more data than needed.

Practical tips

  • Name files by id, never by the original file name from the user, and keep the original in metadata.
  • Store the path in your database, not a temporary signed URL.
  • Delete the file when you delete the row that points to it, or you will pay for orphans.
  • Use resumable uploads for large files and mobile networks.
  • Set cache headers on public files (cacheControl in Supabase upload options, metadata in Firebase).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where are access policies for Supabase Storage written?

    Supabase stores object metadata in Postgres, so its access control is ordinary RLS on storage.objects.
  2. 2. Why is a Firebase getDownloadURL link not suitable for private contracts?

    The link contains a long-lived token. Use rules with authenticated access or short-lived signed links for private files.
  3. 3. What makes a signed URL stop working after its lifetime?

    The server verifies the signature and compares the expiry with the current time.
  4. 4. Which is the safest layout for per-user private files?

    A user-id folder lets a simple rule or policy tie each path to its owner.

Summary

  • Files live in buckets under path-like keys; the database should store the path.
  • Firebase uses Storage Security Rules; Supabase uses RLS policies on storage.objects and public or private buckets.
  • Use public buckets only for truly public files; use private buckets and short-lived signed URLs for the rest.
  • Enforce size and type limits on the server side, and resize images to the size you display.
  • A signed URL binds a path and an expiry to a signature the server can verify.

Next: Cloud Functions and Edge Functions