Firestore Emulator Seed Data: Seeded JSON Fixtures for Rules Tests
Firestore emulator seed data tends to start as a few setDoc calls in a
beforeEach: one user, one document, maybe a hand-built Timestamp. That
gets the first security rules test passing. It stops working once the
rules check owners, references and required fields, because every
allow/deny branch needs a document with exactly the right shape, and
those shapes end up scattered across test files. This post moves the
data into one committed, seeded JSON fixture and loads it into the local
emulator with the Admin SDK: batched writes, document IDs taken from the
fixture, subcollections, and Timestamps, GeoPoints and references
converted from plain JSON. The same fixture then drives
@firebase/rules-unit-testing tests against rows planted to hit each
branch: another user's document, one missing a required field, and one
owned by someone other than the site's owner.
JsonFabrica generates the fixture. It's a JSON-over-HTTP API (plus an
MCP server for AI coding assistants). There's no Firebase package or
plugin. A short shell script calls the API and commits the JSON, and your own seeding script loads that file
into the emulator. JsonFabrica never talks to Firestore. If you're on
MongoDB instead, MongoDB test data covers
Extended JSON and mongoimport; for seeding in general, independent of
the database, see
how to seed a database for local development.
Everything below ran in a throwaway project: firebase-tools 15.37.0
(Firestore emulator 1.22.0) on OpenJDK 21, firebase-admin 14.5.1,
@firebase/rules-unit-testing 6.0.0 with firebase 13.4.0, and
Vitest 5.1.2 on Node 24. The fixture was rendered with the JsonFabrica
template engine, and the regen script ran against a local stand-in for
the generate API that uses the same engine. The outputs shown come from
those runs. I didn't run any of it against a real Firebase project:
everything used a demo- project ID, which only works with emulators.
Why Firestore emulator seed data is awkward
The running example is a field inspection app. users/{uid} holds
profiles. sites/{siteId} holds the sites a user owns, with a location
and a creation time. Each site has an inspections subcollection, and
every inspection points at the user who did it. Four things make test
data for this harder than it looks:
- There's no JSON import. Firestore has no
mongoimportorCOPY FROM. The emulator's--importflag reads only a snapshot that the emulator itself exported, and that snapshot isn't JSON. Getting a JSON file in means writing documents yourself. - JSON doesn't have Firestore's types. A
createdAtwritten as an ISO string is a string in Firestore, not aTimestamp, so a rule checkingcreatedAt is timestampdenies it. The same goes forGeoPointandDocumentReference. Something has to convert values on the way in. - Subcollections are separate writes. Nesting an
inspectionsarray inside a site in JSON doesn't create a subcollection. It creates an array field. Every child document needs its own path and its own write. - Rules tests need exact shapes. A rule that compares
resource.data.inspectorwith the caller's user document only gets exercised if some document has an inspector who isn't the site owner. A rule that requireslocationon update only gets exercised if some stored document lacks it. Random data rarely produces those cases, so they have to be planted.
One detail makes planting possible. The Admin SDK bypasses security
rules, so a seeding script can write documents that your rules would
reject from a client, such as a site written before location became
required. That's exactly the legacy data your rules have to cope with.
Firestore test data from one seeded template
The fixture is generated from one template. It has two top-level
collections, users and sites, and each site carries its inspections
under a $sub key. Values Firestore stores as special types are tagged
objects: $timestamp, $geo and $ref.
{
"users": [
<for(u, 1, 4)><if(getVar('u') > 1)>,<endIf>
{
"id": "u<appendBefore('0', getVar('u'), 2)>",
"displayName": "<getRandomFullName()>",
"email": "<getRandomEmail('example.test')>",
"role": <if(getVar('u') == 4)>"auditor"<else>"inspector"<endIf>
}<end_for>
],
"sites": [
<for(s, 1, getParam('sites', 6))><if(getVar('s') > 1)>,<endIf>
<if(getVar('s') == 2)><setVar('owner', 'u02')>
<elseIf(getVar('s') <= 3)><setVar('owner', 'u01')>
<else><setVar('owner', getRandomElement('u01', 'u02', 'u03'))><endIf>
{
"id": "site-<appendBefore('0', getVar('s'), 3)>",
"name": "<getRandomCity()> <getRandomElement('depot',
'substation', 'warehouse', 'pump station')>",
"ownerId": "<getVar('owner')>",
<if(getVar('s') != 3)>
"location": { "$geo": [<getRandomNumber(47, 55, 5)>,
<getRandomNumber(5, 15, 5)>] },
<endIf>
"createdAt": { "$timestamp": "<getRandomDate(
'2025-01-01T00:00:00Z', '2025-12-31T23:59:59Z')>" },
"$sub": {
"inspections": [
<for(k, 1, getRandomNumber(1, 3))><if(getVar('k') > 1)>,<endIf>
{
"id": "insp-<appendBefore('0', getVar('k'), 2)>",
"inspector": { "$ref": "users/<if(getVar('s') == 1
&& getVar('k') == 1)>u03<else><getVar('owner')><endIf>" },
"status": "<getRandomElement('passed', 'failed', 'follow-up')>",
"notes": "<getRandomTextWithSpaces(20, 50)>",
"inspectedAt": { "$timestamp": "<getRandomDate(
'2026-01-01T00:00:00Z', '2026-06-30T23:59:59Z')>" }
}<end_for>
]
}
}<end_for>
]
}
What each part does:
- Document IDs are in the data. Every row has an
id, built withappendBeforeas a zero-padded loop position:u01,site-003,insp-02. The seeding script uses it as the document ID, so tests can addresssites/site-003directly and the IDs stay the same at any seed. - Planted rows come from the loop position. Template logic has
comparisons (
==,!=,<,<=,>,>=) and&&/||, but no arithmetic, so each edge case is tied to a fixed position. Site 2 is always owned byu02: another user's document, fromu01's point of view. Site 3 belongs tou01and has nolocation: a document missing a required field. The first inspection of site 1 was done byu03althoughu01owns the site: a document whose owner isn't the site's owner. User 4 is the onlyauditor. The control flow docs coverforandif/elseIf/else. - One variable, because it's read in several places.
owneris set once per site and read byownerIdand by every inspection'sinspectorreference, which keeps the inspections consistent with their site. Everything else is inline. - Loop bounds can be function calls. The site count comes from
getParamwith a default of 6, and each site gets one to three inspections fromgetRandomNumber. Bounds are inclusive. The<if(getVar('s') > 1)>,<endIf>guard puts a comma before every element except the first, so the arrays stay valid JSON. - Types are tagged, not guessed.
{"$timestamp": "..."},{"$geo": [lat, lng]}and{"$ref": "users/u03"}say what each value should become. A converter that guesses types from string formats will sooner or later turn a note that happens to look like a date into aTimestamp. The$prefix and the$subkey are this post's convention, not a Firestore or JsonFabrica format; pick any marker your own field names never use.
Rendered with seed 20261130, the fixture has 4 users, 6 sites and 13
inspections. Here's the planted site 3, trimmed to its first
inspection. There's no location key at all:
{
"id": "site-003",
"name": "Akureyri depot",
"ownerId": "u01",
"createdAt": {
"$timestamp": "2025-07-19T23:59:07.830Z"
},
"$sub": {
"inspections": [
{
"id": "insp-01",
"inspector": {
"$ref": "users/u01"
},
"status": "follow-up",
"notes": "recipio feribus grava condicio gradire dicum v",
"inspectedAt": {
"$timestamp": "2026-03-15T09:16:23.102Z"
}
}
]
}
}
Regenerating the fixture with the generate API
The regen script is the only code that calls JsonFabrica. It sends the
raw template to
POST /v1/templates/generate, which
renders a template without saving it, and writes the result to
fixtures/inspections.json:
#!/usr/bin/env bash
# Regenerate fixtures/inspections.json from scripts/inspections.tmpl.
# scripts/regen-fixture.sh # pinned seed: no diff
# scripts/regen-fixture.sh 48151623 # rebuild with another seed
set -euo pipefail
API=${JSONFABRICA_URL:-https://api.jsonfabrica.com}
SEED=${1:-20261130} # change only when you mean to replace the data
OUT=fixtures/inspections.json
trap 'rm -f request.json response.json' EXIT
jq -n --rawfile body scripts/inspections.tmpl --argjson seed "$SEED" \
'{body: $body, seed: $seed, params: {sites: 6}}' > request.json
if ! curl -sS --fail-with-body -X POST "$API/v1/templates/generate" \
-H "Authorization: Bearer ${JSONFABRICA_API_KEY:?set the API key}" \
-H "Content-Type: application/json" \
-d @request.json -o response.json; then
cat response.json >&2; exit 1
fi
jq '.data' response.json > "$OUT"
echo "wrote $OUT (seed $(jq .meta.seed response.json))"
The response is { data, meta }. data is the generated document and
meta.seed is the seed that was used, so the script writes data to
the file and prints the seed. With the same template, seed and
parameters the output is the same: two runs with the pinned seed
produced byte-identical files. jq --rawfile puts the template into the
request body without escaping it by hand.
Commit the template, the script and fixtures/inspections.json
together. Seeding and tests only read the committed file, so they need
no API key and no network, and the data changes only when someone reruns
the script and the diff shows up in review.
Seeding the Firestore emulator with the Admin SDK
The emulator needs a firebase.json. This one runs only Firestore,
pins its port and points at the rules file:
{
"firestore": { "rules": "firestore.rules" },
"emulators": {
"firestore": { "host": "127.0.0.1", "port": 8080 },
"ui": { "enabled": false }
}
}
Start it with a demo- project ID:
npx firebase emulators:start --only firestore --project demo-inspections
The Firestore emulator runs on Java, so you need a JDK on the machine.
firebase-tools 15 needs Java 21 or newer (older JDKs fail with
"firebase-tools no longer supports Java version before 21"); I used
OpenJDK 21. A project ID starting with demo- tells firebase-tools
there's no real project behind it, so nothing can reach production by
accident and you don't need to log in.
The seeding script, scripts/seed-firestore.mjs, reads the fixture,
converts the tagged values and writes every document in batches:
// Load fixtures/inspections.json into the Firestore emulator.
// FIRESTORE_EMULATOR_HOST=127.0.0.1:8080 node scripts/seed-firestore.mjs
import { readFile } from 'node:fs/promises';
import { pathToFileURL } from 'node:url';
import { initializeApp } from 'firebase-admin/app';
import { getFirestore, Timestamp, GeoPoint } from 'firebase-admin/firestore';
const BATCH_LIMIT = 500;
// Plain JSON -> Firestore types, using the fixture's tagged objects.
function toFirestore(db, value) {
if (Array.isArray(value)) return value.map((v) => toFirestore(db, v));
if (value === null || typeof value !== 'object') return value;
if ('$timestamp' in value) {
return Timestamp.fromDate(new Date(value.$timestamp));
}
if ('$geo' in value) return new GeoPoint(value.$geo[0], value.$geo[1]);
if ('$ref' in value) return db.doc(value.$ref);
return Object.fromEntries(
Object.entries(value).map(([k, v]) => [k, toFirestore(db, v)]),
);
}
// One { ref, data } per document, subcollections included.
function* documents(db, collectionPath, rows) {
for (const { id, $sub = {}, ...fields } of rows) {
const ref = db.collection(collectionPath).doc(id);
yield { ref, data: toFirestore(db, fields) };
for (const [name, children] of Object.entries($sub)) {
yield* documents(db, `${ref.path}/${name}`, children);
}
}
}
export async function seed(db, fixture) {
const docs = Object.entries(fixture).flatMap(
([collection, rows]) => [...documents(db, collection, rows)],
);
for (let i = 0; i < docs.length; i += BATCH_LIMIT) {
const batch = db.batch();
for (const { ref, data } of docs.slice(i, i + BATCH_LIMIT)) {
batch.set(ref, data);
}
await batch.commit();
}
return docs.length;
}
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
if (!process.env.FIRESTORE_EMULATOR_HOST) {
throw new Error('FIRESTORE_EMULATOR_HOST is not set; refusing to seed');
}
const db = getFirestore(initializeApp({ projectId: 'demo-inspections' }));
const fixture = JSON.parse(
await readFile(new URL('../fixtures/inspections.json', import.meta.url)),
);
console.log(`seeded ${await seed(db, fixture)} documents`);
}
Run it while the emulator is up:
$ FIRESTORE_EMULATOR_HOST=127.0.0.1:8080 node scripts/seed-firestore.mjs
seeded 23 documents
How it works:
FIRESTORE_EMULATOR_HOSTis the switch. When it's set, the Admin SDK sends every Firestore call to that host and port instead of to Google, and doesn't need credentials. The script refuses to run without it, so a missing variable can't turn a local seed into a write to a real project.- The fixture's
idbecomes the document ID. Destructuring takesidand$subout of each row, and the remaining fields become the document. Nothing ends up with an auto-generated ID, so tests and the fixture agree on paths. - Subcollections are walked recursively. Each entry under
$subbecomes a collection under the parent document's path, heresites/site-001/inspections. A$subinside an inspection would work the same way, one level deeper. - Tagged values are converted on the way in. Reading the seeded
documents back with the Admin SDK,
createdAtwas aTimestamp,locationaGeoPointandinspectoraDocumentReferencewith pathusers/u03. - Writes go in batches of up to 500. A batch commits all of its
writes or none. Older Firestore docs capped a batch at 500 writes.
The current quotas page lists no write count, only a 10 MiB request
size, so chunking at 500 is a conservative habit rather than a hard
rule. The emulator accepted 600 writes in one batch in my run, which
says nothing about production. For
very large fixtures, the Admin SDK's
BulkWriteris the other option. setoverwrites, but doesn't delete. Re-running the script replaces every document in the fixture. Documents that aren't in the fixture, like the ones a test created, stay where they are. That's why the next step clears the database first.
seed() is exported, so the rules tests below call the same function
the command line does. There's one conversion path, and it's tested
along with the rules.
If you aren't using Firebase at all and want a real database in a container instead, Testcontainers test data covers the same seed-from-a-committed-file approach for Postgres and other SQL databases.
Clearing the Firestore emulator between tests
The emulator has a REST endpoint that deletes every document in a project's database:
curl -X DELETE "http://127.0.0.1:8080/emulator/v1/projects/\
demo-inspections/databases/(default)/documents"
It returned 200 and left the database empty, without restarting the
emulator. Host, port and project ID have to match your emulator. The
endpoint is specific to the emulator; there's no equivalent on a real
Firestore database.
In rules tests you don't need to call it yourself.
testEnv.clearFirestore() from @firebase/rules-unit-testing sends
the same DELETE. Clear, then seed, before every test. Each test then
starts from exactly the fixture, whatever the previous test wrote.
How to test Firestore security rules against planted rows
These are the rules under test, firestore.rules. Owners read and
update their sites, an auditor custom claim reads everything, updates
must keep a site valid, and an inspection can be edited only by the
user its inspector reference points to:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function signedIn() { return request.auth != null; }
function me() {
return /databases/$(database)/documents/users/$(request.auth.uid);
}
function isAuditor() { return request.auth.token.role == 'auditor'; }
function validSite(d) {
return d.keys().hasAll(['name', 'ownerId', 'location', 'createdAt'])
&& d.location is latlng && d.createdAt is timestamp;
}
function siteOwner(siteId) {
return get(/databases/$(database)/documents/sites/$(siteId))
.data.ownerId;
}
match /users/{uid} {
allow read, write: if signedIn() && request.auth.uid == uid;
}
match /sites/{siteId} {
allow read: if signedIn()
&& (resource.data.ownerId == request.auth.uid || isAuditor());
allow create: if signedIn()
&& request.resource.data.ownerId == request.auth.uid
&& validSite(request.resource.data);
allow update: if signedIn()
&& resource.data.ownerId == request.auth.uid
&& request.resource.data.ownerId == resource.data.ownerId
&& validSite(request.resource.data);
match /inspections/{inspectionId} {
allow read: if signedIn()
&& (siteOwner(siteId) == request.auth.uid
|| resource.data.inspector == me() || isAuditor());
allow create: if signedIn()
&& siteOwner(siteId) == request.auth.uid
&& request.resource.data.inspector == me();
allow update: if signedIn()
&& resource.data.inspector == me()
&& request.resource.data.inspector == resource.data.inspector;
}
}
}
}
The tests run in Vitest, with @firebase/rules-unit-testing and the
firebase web SDK as dev dependencies. They'd look almost the same in
Jest; Jest and Vitest test data covers
importing JSON fixtures in both runners. test/firestore.rules.test.js:
import { readFileSync } from 'node:fs';
import { afterAll, beforeAll, beforeEach, expect, test } from 'vitest';
import {
assertFails, assertSucceeds, initializeTestEnvironment,
} from '@firebase/rules-unit-testing';
import {
doc, getDoc, setDoc, updateDoc, GeoPoint, Timestamp,
} from 'firebase/firestore';
import { initializeApp } from 'firebase-admin/app';
import { getFirestore } from 'firebase-admin/firestore';
import fixture from '../fixtures/inspections.json' with { type: 'json' };
import { seed } from '../scripts/seed-firestore.mjs';
const projectId = 'demo-inspections';
const auditor = fixture.users.find((u) => u.role === 'auditor');
let testEnv;
let admin;
beforeAll(async () => {
// Host and port come from FIRESTORE_EMULATOR_HOST.
testEnv = await initializeTestEnvironment({
projectId,
firestore: { rules: readFileSync('firestore.rules', 'utf8') },
});
admin = getFirestore(initializeApp({ projectId }));
});
beforeEach(async () => {
await testEnv.clearFirestore();
await seed(admin, fixture);
});
afterAll(() => testEnv.cleanup());
const as = (uid, claims) => testEnv.authenticatedContext(uid, claims)
.firestore();
test('fixture still has its planted rows', () => {
const site = (id) => fixture.sites.find((s) => s.id === id);
expect(site('site-002').ownerId).toBe('u02');
expect(site('site-003')).not.toHaveProperty('location');
expect(site('site-001').$sub.inspections[0].inspector.$ref)
.toBe('users/u03');
expect(auditor.id).toBe('u04');
});
test('owner reads own site, not another user\'s', async () => {
const db = as('u01');
await assertSucceeds(getDoc(doc(db, 'sites/site-001')));
await assertFails(getDoc(doc(db, 'sites/site-002')));
await assertFails(getDoc(doc(testEnv.unauthenticatedContext()
.firestore(), 'sites/site-001')));
});
test('auditor custom claim reads any site', async () => {
const db = as(auditor.id, { role: auditor.role });
await assertSucceeds(getDoc(doc(db, 'sites/site-002')));
});
test('legacy site without location must be repaired on update',
async () => {
const site = doc(as('u01'), 'sites/site-003');
await assertFails(updateDoc(site, { name: 'Renamed' }));
await assertSucceeds(updateDoc(site, {
name: 'Renamed', location: new GeoPoint(50.1, 8.7),
}));
});
test('site owner can read but not edit a contractor\'s inspection',
async () => {
const path = 'sites/site-001/inspections/insp-01';
await assertSucceeds(getDoc(doc(as('u01'), path)));
await assertFails(updateDoc(doc(as('u01'), path), { status: 'passed' }));
await assertSucceeds(
updateDoc(doc(as('u03'), path), { status: 'passed' }));
await assertFails(getDoc(doc(as('u03'), 'sites/site-001')));
});
test('creates must name the caller as owner or inspector', async () => {
const db = as('u01');
await assertFails(setDoc(doc(db, 'sites/site-new'), {
name: 'Bonn depot', ownerId: 'u02',
location: new GeoPoint(50.7, 7.1), createdAt: Timestamp.now(),
}));
const insp = doc(db, 'sites/site-001/inspections/insp-new');
await assertFails(setDoc(insp, { inspector: doc(db, 'users/u03') }));
await assertSucceeds(setDoc(insp, { inspector: doc(db, 'users/u01') }));
});
How the pieces fit:
initializeTestEnvironmentloads the rules. It sends the rules file to the emulator fordemo-inspectionsand finds the emulator through environment variables such asFIRESTORE_EMULATOR_HOST. You can also passhostandportin thefirestoreoptions.- Seeding uses the Admin SDK, with rules bypassed.
beforeEachclears the database and calls the sameseed()as the command line. The Admin SDK and the web SDK run in the same Vitest process against the same emulator. For a one-off document inside a single test,testEnv.withSecurityRulesDisabled(async (ctx) => { … })runs a callback with a web SDK context that ignores rules. - Each planted row drives one branch.
site-002is the other user's document thatu01must not read.site-003is the stored document missinglocation: renaming it alone is denied because the result still isn't a valid site, and adding a location in the same update is allowed.site-001/inspections/insp-01belongs tou03, so the site owner can read it but not edit it, andu03can edit it even thoughu03can't read the site itself. - Custom claims go in
authenticatedContext. Its second argument becomes the token's claims, so{ role: 'auditor' }shows up in the rules asrequest.auth.token.role. The test takes the uid and role from the fixture's auditor row rather than repeating them. For building the full matrix of roles and claims, see mock JWT test data for RBAC. assertFailschecks for a permission error. It passes only when the promise rejects with a permission-denied error; any other error, such as a connection failure, fails the test. It can't tell why access was denied, though. A read from a mistyped path is usually denied too, which is one more reason to use the IDs from the fixture rather than retyping paths by hand.- The first test guards the fixture. If someone edits the template and moves a planted row, that test fails with a clear message instead of a rules test quietly losing its edge case.
To run the suite, let firebase-tools start the emulator, run the command and stop the emulator again:
npx firebase emulators:exec --only firestore \
--project demo-inspections 'vitest run'
emulators:exec sets FIRESTORE_EMULATOR_HOST for the command it
runs, so neither the tests nor the CI job have to. Trimmed to the lines
that matter, the run looked like this:
i Running script: vitest run
Test Files 1 passed (1)
Tests 6 passed (6)
✔ Script exited successfully (code 0)
To check that the type conversion actually matters, I broke the seeder
on purpose twice and ran the suite again. With references stored as
plain "users/u03" strings, one test failed: u03 could no longer
update the contractor's inspection, because the rule compares the
stored value with a document path. The output, with the test name
shortened:
FAIL ... > site owner can read but not edit a contractor's inspection
FirebaseError: 7 PERMISSION_DENIED:
evaluation error at L40:26 for 'update' @ L40, false for 'update' @ L40
With timestamps stored as ISO strings, the location repair failed
instead: the site was still invalid because createdAt is timestamp
was false. In both cases, data shaped slightly wrong turned an allow
into a deny, and only a test that used the seeded data noticed.
Firebase emulator import data: snapshots vs a seed script
The emulator has its own way to save and restore data. While it's
running, firebase emulators:export ./emulator-data writes its state
to a directory. Starting it with --import=./emulator-data loads that
state back, and --export-on-exit writes the state out again when the
emulator shuts down:
npx firebase emulators:start --only firestore --project demo-inspections \
--import=./emulator-data --export-on-exit
I exported the seeded emulator, restarted it with --import, and all
documents, subcollections included, were back. The export is a
metadata file plus binary data files, not JSON. You can commit the
directory, but a pull request can't show what changed inside it.
The two approaches fit different jobs:
- Use a snapshot to restore a known full state quickly. A large demo dataset for manual testing, or the state someone built up by clicking through the app, loads straight from disk with no script. It's the right tool when nobody needs to read or edit the data, only to get it back.
- Use a seeding script with a JSON fixture when the data is part of your tests. The fixture is reviewable in a diff, can be regenerated at a different size or seed, and can plant the exact edge documents a rules test needs. The conversion code is tested along with everything else.
Many projects use both: the script builds the baseline for tests, and
developers keep a personal snapshot for manual work. Be careful when
combining --import and --export-on-exit on the same directory. In
my run, a document I added while the emulator was running ended up in
the snapshot on shutdown, overwriting the baseline I had imported. For
a committed baseline, import without --export-on-exit,
or export to a different directory.
FAQ
How do I import JSON data into the Firestore emulator?
Firestore has no built-in JSON import, in the emulator or in production. The emulator's --import flag only reads a directory written by firebase emulators:export or --export-on-exit, which is a binary snapshot, not JSON. To load a JSON file, write a short script that reads it and writes each document with the Admin SDK while FIRESTORE_EMULATOR_HOST points at the emulator.
How do I clear the Firestore emulator between tests?
Send DELETE to http://127.0.0.1:8080/emulator/v1/projects/YOUR_PROJECT_ID/databases/(default)/documents, adjusting host, port and project ID to your setup. It removes every document in that project's default database without restarting the emulator. In rules tests, testEnv.clearFirestore() from @firebase/rules-unit-testing calls the same endpoint. Clear before you seed, because set() overwrites the documents in your fixture but leaves anything else a previous test created.
How do I store a Timestamp, GeoPoint or reference when seeding Firestore from JSON?
JSON has no type for them, so mark them in the fixture and convert them in the seeding script. A tagged object such as {"$timestamp": "2026-03-15T09:16:23Z"} becomes Timestamp.fromDate, {"$geo": [lat, lng]} becomes a GeoPoint, and {"$ref": "users/u01"} becomes db.doc(path). If you write the raw strings instead, rules that check is timestamp or compare a reference with a document path will deny requests they should allow.
How do I test Firestore security rules locally?
Run the Firestore emulator and use @firebase/rules-unit-testing from a test runner such as Vitest or Jest. initializeTestEnvironment loads your rules file into the emulator, authenticatedContext gives you a Firestore client signed in as a given uid with optional custom claims, and assertSucceeds and assertFails check whether the rules allowed each read or write. Seed the data each test needs before it runs, with rules bypassed.
Should I use Firebase emulator export and import or a seed script?
Use --import with an exported snapshot when you want to restore a known, complete state quickly and nobody needs to read or edit it, for example a large demo dataset. Use a seed script with a committed JSON fixture when the data should be reviewed in pull requests, regenerated with a different size or seed, or changed to plant specific edge-case documents for rules tests. Many projects use both.
Does JsonFabrica have a Firebase or Firestore package or plugin?
No. JsonFabrica is a JSON-over-HTTP API (plus an MCP server for AI coding assistants). It has no Firebase or Firestore package, plugin, SDK or database connector. You write a small regen script that sends a template and a seed to the API and commits the JSON it returns. Your own seeding script then loads that committed file into the emulator with the Firebase Admin SDK, and your tests never call JsonFabrica.
The fixture behind all of this came from one template and one call to JsonFabrica's generate endpoint, with planted rows at fixed positions and the same output for the same seed. The templates API reference has the request format for rendering your own Firestore emulator seed data.
Generate realistic test data with JsonFabrica
Describe the shape of your data once, then generate as many fresh, realistic JSON documents as you need via a simple API call.