Providing Flutter + Firebase boilerplate with security rules and emulator tests
This outlines a Flutter project setup with Firebase, Firestore security rules restricting user access, local emulator configuration, and a Node.js test script using @firebase/rules-unit-testing to verify user isolation before deployment. It includes directory structure, key config files, minimal Flutter code, Firestore rules, emulator setup, and test instructions.
Below is a minimal boilerplate you can drop into a new Flutter project with Firebase + Firestore, set up to use the local emulator suite and with a unit test (via the Firebase Rules Unit Testing SDK) that verifies user A cannot read user B’s private document before you deploy.
1) Project layout (relevant files)
your_app/
├─ lib/
│ └─ main.dart
├─ pubspec.yaml
├─ firebase.json
├─ firestore.rules
├─ firestore.indexes.json
├─ test/
│ └─ security_rules.test.js # Node test for Firestore rules
├─ package.json # For running rules tests
└─ .firebaserc
2) Flutter dependencies (pubspec.yaml)
name: your_app
description: A Flutter + Firebase boilerplate
publish_to: 'none'
environment:
sdk: ">=2.19.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
firebase_core: ^2.0.0
cloud_firestore: ^4.0.0
dev_dependencies:
flutter_test:
sdk: flutter
Make sure to run flutter pub get after saving.
3) Initialize Firebase in Flutter (lib/main.dart)
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'firebase_options.dart'; // generated by `flutterfire configure`
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Firebase Boilerplate',
home: Scaffold(
appBar: AppBar(title: const Text('Firestore Boilerplate')),
body: FutureBuilder<DocumentSnapshot>(
future: FirebaseFirestore.instance
.collection('users')
.doc('exampleUserId')
.get(),
builder: (context, snapshot) {
if (snapshot.hasError) return const Text('Error loading doc');
if (!snapshot.hasData) return const CircularProgressIndicator();
final data = snapshot.data!.data();
return Text('User doc: $data');
},
),
),
);
}
}
Run flutterfire configure to create lib/firebase_options.dart and link your Firebase project. Use emulators when running locally with --dart-define=USE_EMULATOR=true if you add logic for that (see note below).
4) Firestore security rules (firestore.rules)
These rules allow each authenticated user to read/write only their own document at /users/{userId} and its subcollections.
/// Firestore Security Rules
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// All user-specific data lives under /users/{userId}
match /users/{userId}/{document=**} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}
5) Local emulator configuration (firebase.json)
{
"emulators": {
"functions": {
"port": 5001
},
"firestore": {
"port": 8080
},
"auth": {
"port": 9099
},
"ui": {
"enabled": true
}
},
"firestore": {
"rules": "firestore.rules",
"indexes": "firestore.indexes.json"
}
}
.firebaserc (pointing to your project):
{
"projects": {
"default": "your-firebase-project-id"
}
}
Start emulators locally with:
firebase emulators:start --only firestore,auth
6) Node test setup (package.json)
Use the official Firebase Rules Unit Testing library to test security rules against the emulator.
{
"name": "firestore-rules-tests",
"private": true,
"devDependencies": {
"@firebase/rules-unit-testing": "^2.0.0",
"firebase-admin": "^11.0.0",
"firebase-functions": "^4.0.0"
},
"scripts": {
"test:rules": "node ./test/security_rules.test.js"
}
}
Install with:
npm install
7) Firestore rules test (test/security_rules.test.js)
This script spins up two authenticated contexts (userA and userB) and verifies user A cannot read B’s document. It runs against the local emulator; no network calls to production.
const fs = require('fs');
const {
initializeTestEnvironment,
assertFails,
assertSucceeds
} = require('@firebase/rules-unit-testing');
const PROJECT_ID = "demo-test-project"; // can match .firebaserc or be any id for tests
const FIRESTORE_RULES = fs.readFileSync('firestore.rules', 'utf8');
let testEnv;
before(async () => {
testEnv = await initializeTestEnvironment({
projectId: PROJECT_ID,
firestore: {
rules: FIRESTORE_RULES
}
});
});
after(async () => {
await testEnv.cleanup();
});
describe("Firestore Security Rules", () => {
it("user A cannot read user B's private doc", async () => {
// Create test contexts for two different users
const userA = testEnv.authenticatedContext("userA");
const userB = testEnv.authenticatedContext("userB");
// Seed data in userB's document as admin
const adminContext = testEnv.unauthenticatedContext();
const adminFirestore = adminContext.firestore();
await adminFirestore.collection("users").doc("userB").set({ secret: "shh" });
// userB reading own doc succeeds
const userBFirestore = userB.firestore();
await assertSucceeds(userBFirestore.collection("users").doc("userB").get());
// userA reading userB's doc must fail
const userAFirestore = userA.firestore();
await assertFails(userAFirestore.collection("users").doc("userB").get());
});
it("user can read/write their own doc", async () => {
const user = testEnv.authenticatedContext("myUserId");
const db = user.firestore();
await assertSucceeds(db.collection("users").doc("myUserId").set({ foo: "bar" }));
await assertSucceeds(db.collection("users").doc("myUserId").get());
});
});
Run locally (emulator) with:
npm run test:rules
Ensure your emulators are not running in the same terminal if you use initializeTestEnvironment (it spins up an in-process emulator). If you prefer to reuse firebase emulators:start, configure port and set emulators: { firestore: { host: "localhost", port: 8080 } } in initializeTestEnvironment.
8) Optional: using the Firestore emulator in Flutter during development
If you want to point your Flutter app at the emulator (so you don’t touch production while testing the UI), you can add the following snippet to your main.dart:
import 'package:flutter/foundation.dart' show kIsWeb;
// After Firebase.initializeApp(...)
if (const bool.fromEnvironment('USE_EMULATOR')) {
// Must be set before any reads/writes
FirebaseFirestore.instance.useFirestoreEmulator('localhost', 8080);
}
Then run:
flutter run --dart-define=USE_EMULATOR=true
9) Deploying rules after tests pass
Once your rules tests pass:
firebase deploy --only firestore:rules
Always run npm run test:rules (or equivalent) before deploying to ensure you’re not opening unintended access.
This boilerplate gives you:
- A minimal Flutter app wired to Firebase.
- Strict, per-user Firestore security rules.
- Local emulator suite configuration.
- A pre-deploy unit test ensuring user A cannot read user B’s private documents.