Skip to main content

Firebase Sync Examples

Copy-pasteable examples for syncing Strata Storage through Firebase (Cloud Firestore or the Realtime Database). See the Firebase guide for the full configuration reference.

Install the optional peer dependency with yarn add firebase.

Firestore: cross-device profile​

import { Strata, defineStorage } from 'strata-storage';
import { enableFirebaseSync } from 'strata-storage/firebase';

const storage = defineStorage();

await enableFirebaseSync(storage, {
apiKey: 'YOUR_API_KEY',
authDomain: 'your-app.firebaseapp.com',
projectId: 'your-app',
appId: 'YOUR_APP_ID',
firestore: true,
});

// Write/read against Firestore
await storage.set('profile', { name: 'Ada', theme: 'dark' }, { storage: 'firestore' });
const profile = await storage.get('profile', { storage: 'firestore' });

// React to remote changes from other devices/users
const unsubscribe = storage.subscribe(
(change) => {
if (change.source === 'remote') {
console.log('Remote update:', change.key, change.newValue);
}
},
{ storage: 'firestore' },
);

// later: unsubscribe();

Realtime Database: shared counter​

import { Strata, defineStorage } from 'strata-storage';
import { enableFirebaseSync } from 'strata-storage/firebase';

const storage = defineStorage();

await enableFirebaseSync(storage, {
apiKey: 'YOUR_API_KEY',
authDomain: 'your-app.firebaseapp.com',
projectId: 'your-app',
appId: 'YOUR_APP_ID',
realtimeDatabase: true,
});

await storage.set('counter', 0, { storage: 'realtime' });

storage.subscribe(
(change) => console.log('counter is now', change.newValue),
{ storage: 'realtime' },
);

Encrypt before it leaves the device​

The Firebase adapters store values as-is unless encryption is enabled on the Strata instance. Configure encryption before the first write, then pass a password for each encrypted operation:

const encryptedStorage = defineStorage({ encryption: { enabled: true } });
await enableFirebaseSync(encryptedStorage, {
apiKey: 'YOUR_API_KEY',
authDomain: 'your-app.firebaseapp.com',
projectId: 'your-app',
appId: 'YOUR_APP_ID',
firestore: true,
});
await encryptedStorage.set('secret', sensitiveValue, {
storage: 'firestore',
encrypt: true,
encryptionPassword: userProvidedPassword,
});

Guarded enable​

import { enableFirebaseSync, isFirebaseAvailable } from 'strata-storage/firebase';

if (await isFirebaseAvailable()) {
await enableFirebaseSync(storage, config);
} else {
console.warn('Install the optional `firebase` dependency to enable cloud sync.');
}

See also​