A user uploads a contract to your Flutter app. The Firestore document that describes it is locked down, so other accounts cannot read its title, owner or upload date. Then the same user copies the file link from the app and pastes it into a chat, or a support screen logs it, and anyone who opens that link sees the PDF without signing in. The record was private. The file was not.
This happens because Firebase checks the record and the file separately. Firestore Security Rules protect the document. Cloud Storage Security Rules protect the object. A download URL from getDownloadURL() is a third thing: once it exists, it opens the file for whoever holds it. To keep user files private, give Storage its own ownership rules, store the object path instead of a download URL, fetch private bytes through the SDK so every read is checked, and test the cases where access should end.
The examples below use a synthetic document flow: one files collection in Firestore, one PDF per document, and demo users named alice and bob. None of the code has been executed for this article. Each section says what to run before you rely on it.
Why a private Firestore record does not hide the file
Firestore rules and Storage rules are deployed and evaluated as separate rule sets. A request to read files/doc1 in Firestore never consults your Storage rules, and a request for private/doc1/contract.pdf in Storage never consults your Firestore rules unless the Storage rule asks for a Firestore document explicitly. Firebase's Storage Security Rules overview describes rules that grant access by path and by file metadata such as size and content type. Nothing links them to a Firestore document automatically.
So a project can have careful Firestore rules and a Storage rule written for a quick demo, such as allowing any signed-in user to read everything. Each rule set looks correct when you review it alone. The gap only appears when you compare who can read the record with who can read the bytes it points to.
There is also a second, quieter gap. Many upload flows call getDownloadURL() right after the upload and save the result in the Firestore document. The Reference API for Flutter describes it as a long-lived URL that can be used to access the object. The Admin SDK documentation is blunter about the same kind of URL: "Anyone with this URL can permanently access the file." Storage rules decide who may ask for the URL. After that, the URL works without a Firebase sign-in.
A download URL keeps working after access should end
The rule check happens when the app asks for the URL. Whoever opens the URL later does not need to sign in, so there is no user for a rule to check. Every copy of the link opens the same file.
That changes what "private" means for features that store or pass the URL around:
- A URL saved in a Firestore field is readable by anyone your Firestore rules let read that field, and by anything that logs or caches the document.
- A URL sent in a message, email or support ticket is now outside your app.
- Signing the user out, moving the file to another owner or deleting the Firestore record does not invalidate a URL that someone already has.
Firebase gives you a manual way out. The Firebase console file manager lets you create a new download URL for a file and then revoke the previous one, for example when "an existing one has been too widely shared." That is a console step for an incident, not an access-control system. Treat a download URL as appropriate for files you are willing to make public, like a product image, and keep it away from private documents.
Give the file a path that a rule can check
The next step is to make the Storage rule ask the same question as the Firestore rule: does this user own this document? You can encode the owner in the path, such as users/{uid}/..., and compare it with request.auth.uid, which is the pattern in Firebase's rule conditions guide. It is simple and costs nothing extra per request. Its weakness is that ownership lives in the path, so transferring a file means copying it to a new path.
The alternative keeps one source of truth. Store the file at private/{docId}/{fileName} and let the Storage rule read the owner from the Firestore document with firestore.get(). Cross-service rules have limits that the same guide lists: the path must be fully specified, a single rule evaluation may access no more than two Firestore documents, in a project with several databases only the default one is reachable, the reads count toward Firestore quota and billing, and you must approve the permission that connects the two products when you first deploy.
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /private/{docId}/{fileName} {
function fileRecord() {
return firestore.get(/databases/(default)/documents/files/$(docId)).data;
}
function isOwner() {
return request.auth != null && fileRecord().ownerId == request.auth.uid;
}
allow get: if isOwner();
allow create: if isOwner()
&& request.resource.size < 10 * 1024 * 1024
&& request.resource.contentType == 'application/pdf';
allow delete: if isOwner();
}
}
}
The rule uses the granular operations from the Storage rules syntax guide. It allows get but not list, so a user cannot enumerate other people's folders. It allows create but not update, so an existing file cannot be replaced or have its metadata rewritten by the client. The same guide warns that when several rules match a path, access is granted if any of them allows it. Search your rules file for a broader match, such as a leftover {allPaths=**} rule, that would still open this folder.
The Firestore side needs matching rules. A user may create a record only with their own uid as ownerId, and no client may change ownerId later:
match /files/{docId} {
allow read, delete: if request.auth != null
&& resource.data.ownerId == request.auth.uid;
allow create: if request.auth != null
&& request.resource.data.ownerId == request.auth.uid;
allow update: if request.auth != null
&& resource.data.ownerId == request.auth.uid
&& request.resource.data.ownerId == resource.data.ownerId;
}
Ownership transfer then belongs to trusted server code that updates ownerId. Because the Storage rule reads that field on each request, the next rules-checked read by the old owner is denied and the new owner's read is allowed, without moving the object.
Order matters in the client. The record must exist before the upload, because the Storage rule reads it:
final uid = FirebaseAuth.instance.currentUser!.uid;
final record = FirebaseFirestore.instance.collection('files').doc();
final path = 'private/${record.id}/demo-contract.pdf';
await record.set({
'ownerId': uid,
'storagePath': path,
'status': 'uploading',
});
await FirebaseStorage.instance.ref(path).putData(
pdfBytes,
SettableMetadata(contentType: 'application/pdf'),
);
Store storagePath, not a download URL. When the user deletes a document, delete the Storage object first and the record second. If the record goes first, the owner check can no longer pass, and the object stays behind until server code removes it.
Size and type checks see metadata, not the file
request.resource.size and request.resource.contentType are metadata about the incoming upload. The rule conditions guide lists what request.resource contains, and none of it is the file's bytes. The content type comes from the upload request, which in Flutter is usually the value you set in SettableMetadata. A rule that requires application/pdf rejects honest mistakes and casual misuse. It does not prove the upload is a PDF, and it does not detect malicious content.
If the type has to be true, check the bytes on a server. A Cloud Functions onObjectFinalized trigger runs when a new object is created, and the function can download the object with the Admin SDK, inspect its header, and set the record's status to ready or delete the object. The app then shows a file only when its record says ready. Keep the 10 MB size limit in the rule as well, because it stops oversized uploads before the bytes are stored.
Fetch private bytes through the SDK
For a private file, let the SDK download the bytes with the user's own credentials. Each call is a Storage request that your rules evaluate, so a revoked owner, a deleted record or a signed-out session fails on the next attempt.
| Delivery method | Rules checked on each read | Who can use it | How access ends |
|---|---|---|---|
ref.getData() or ref.writeToFile() | Yes | The signed-in user the rules allow | Change the record, the rules or the session |
getDownloadURL() result | Only when the URL is created | Anyone holding the URL | Create a new URL and revoke the old one in the console |
| Cloud Storage signed URL from your server | Your server decides before signing | Anyone holding the URL until it expires | Expiry, at most 7 days for V4 signing, or key rotation |
In Flutter, getData() loads the whole object into memory and takes a maximum size, which defaults to 10485760 bytes. The Flutter download guide warns that a file larger than available memory will crash the app, so use writeToFile() for large documents on mobile. Firebase's web download guide says direct byte downloads allow "finer-grained access control via Firebase Security Rules," and that browsers need a CORS configuration on the bucket before they can download data directly. Check that configuration before you ship a Flutter web build.
final record = await FirebaseFirestore.instance.doc('files/$docId').get();
final path = record.data()!['storagePath'] as String;
final bytes = await FirebaseStorage.instance.ref(path).getData(10 * 1024 * 1024);
Sometimes you genuinely need a URL, for example to hand a file to a PDF viewer that only accepts links. In that case, issue a short-lived signed URL from server code after your own ownership check. Google's signed URL documentation is clear about the trade: "Anyone who knows the URL can access the resource until the expiration time for the URL is reached," the longest V4 expiration is 7 days, and the page describes no way to cancel one URL early apart from rotating the signing key. Choose minutes, not days, and never store the URL.
Signing out stops future SDK reads, because request.auth is null in the rule. It does not remove bytes your app already saved. If you cache documents on the device, delete that cache in your sign-out handler.
What FlutterFlow does and where custom code starts
FlutterFlow's Upload/Save Media action can upload to Firebase Storage and exposes the result as Widget State > Uploaded File URL for you to preview or save. Its Storage rules page offers a Make Users Uploads Private option that limits access to the user who uploaded the file. Its Storage library describes the URL from its getDownloadUrl action as one that "provides public, read-only access to the file."
Put those together before you call a FlutterFlow upload private. The private-uploads rule governs SDK requests. A URL you save in a document field can still be shared. For private documents, save the storage path in your collection, add the owner check from the rules above if you manage rules outside FlutterFlow, and load the bytes in a custom action that calls getData() or writeToFile(). Display can stay in FlutterFlow widgets once the bytes are on the device.
For the wider Firebase setup around this flow, see the guide to building a Flutter and Firebase SaaS mobile app. If your data is shared by teams rather than owned by one user, the comparison of Firestore rules and Postgres row-level security for multi-tenant apps covers tenant-scoped checks.
Test the cases where access should end
Run these checks against the Firestore and Storage emulators with @firebase/rules-unit-testing, which the rules unit testing guide documents. Use a project ID that starts with demo-, as the library's configuration reference recommends.
import { readFileSync } from "node:fs";
import {
initializeTestEnvironment, assertSucceeds, assertFails,
} from "@firebase/rules-unit-testing";
import { ref, uploadBytes, getBytes } from "firebase/storage";
import { doc, setDoc, deleteDoc } from "firebase/firestore";
const testEnv = await initializeTestEnvironment({
projectId: "demo-private-files",
firestore: { rules: readFileSync("firestore.rules", "utf8") },
storage: { rules: readFileSync("storage.rules", "utf8") },
});
const path = "private/doc1/demo-contract.pdf";
const pdf = new TextEncoder().encode("%PDF-1.7 synthetic demo");
await testEnv.withSecurityRulesDisabled(async (admin) => {
await setDoc(doc(admin.firestore(), "files/doc1"), { ownerId: "alice" });
await uploadBytes(ref(admin.storage(), path), pdf, { contentType: "application/pdf" });
});
const alice = testEnv.authenticatedContext("alice");
const bob = testEnv.authenticatedContext("bob");
const guest = testEnv.unauthenticatedContext();
await assertSucceeds(getBytes(ref(alice.storage(), path)));
await assertFails(getBytes(ref(bob.storage(), path)));
await assertFails(getBytes(ref(guest.storage(), path)));
await assertFails(uploadBytes(
ref(alice.storage(), "private/doc1/large.pdf"),
new Uint8Array(11 * 1024 * 1024),
{ contentType: "application/pdf" },
));
await testEnv.withSecurityRulesDisabled(async (admin) => {
await deleteDoc(doc(admin.firestore(), "files/doc1"));
});
await assertFails(getBytes(ref(alice.storage(), path)));
await testEnv.cleanup();
Run it with both emulators started, for example firebase emulators:exec --only firestore,storage "node private-files.test.mjs". If your emulator version does not evaluate the cross-service firestore.get() call, test that part in a staging project instead of assuming it passes.
Then walk the full matrix, including the cases the emulator script cannot cover:
| Case | Action | Expected result |
|---|---|---|
| Owner | alice reads her file with getData() | Bytes returned |
| Other user | bob reads alice's path | Permission denied |
| Signed out | Read after signOut() | Permission denied; local cache cleared by your handler |
| Oversized upload | alice uploads 11 MB as application/pdf | Upload rejected |
| Wrong declared type | alice uploads with image/png | Upload rejected |
| Deleted metadata | Delete files/doc1, then alice reads | Permission denied |
| Ownership change | Server sets ownerId to bob | alice denied, bob allowed on next read |
| Shared URL | In staging, create a download URL and open it in a private browser window | File opens without sign-in, which is why private flows must not create one |
| Revoked URL | Create a new URL and revoke the old one in the console, then reopen the old link | Old link no longer works |
The shared-URL row tests your delivery code rather than your rules. Run it once against your real delivery code, and if the file opens in a signed-out window, the feature is not private yet.
Limits of this design
The owner check adds a Firestore document read to each Storage request it evaluates, and those reads count toward Firestore quota and billing. A rule evaluation can access at most two Firestore documents, so team folders with membership lookups need a simpler data shape or custom claims. Content-type rules do not validate file contents, and server-side inspection adds a function and a short delay before a file is ready. Anything a user has already downloaded or captured stays with them. None of the rules, Dart or test code here was executed for this article, so run the emulator test and the staging URL check before you rely on them.
Start with the shared-URL row today. Open one private file link from your current build in a signed-out browser window. If it loads, replace the stored URL with the storage path and move that screen to getData().

