Research: Offline-first with Couchbase (look mom, no SaaS \O/)

I’m trying different methods of achieving offline-first for Flutter with those premises:

a) It must work with Firebase Auth (because I don’t want to pay USD 7000/month for authentication)
b) It must be installed using Docker or in bare-metal (since those are waaay cheaper than Cloud SaaS).

I’ve already achieved that using Hasura + Powersync, but since Powersync has some issues, I want to try on Couchbase (more details here: Has anyone used Brick (offline first architecture) in production)

I’ll post my findings here and I’m using this text from my yellow-duck-trainee-ia to guide me in the process:


Couchbase for Flutter: Building an Offline-First App with Firebase Authentication

Before diving into specific implementation details, let’s clarify the various Couchbase products and establish the architecture you’ll need for your offline-first Flutter application with Firebase Authentication integration.

Understanding the Couchbase Ecosystem

The Couchbase ecosystem consists of several complementary products that serve different purposes in a mobile-to-cloud data architecture. Based on your requirements, you’ll need to understand how these components work together:

Couchbase Lite

Couchbase Lite is an embedded NoSQL database that runs directly on client devices. This is what you’ll use in your Flutter application via the cbl package. It provides local data storage, querying capabilities, and synchronization support[7]. Couchbase Lite enables your application to work offline and sync changes when connectivity is restored.

Sync Gateway

Sync Gateway is the critical middleware component that enables bidirectional synchronization between your mobile devices and the backend database. It handles authentication, authorization, and data routing between Couchbase Lite on devices and Couchbase Server in the backend[3]. Sync Gateway is essential for implementing user-based data access control through its channels feature[12].

Couchbase Server

Couchbase Server is the backend database that serves as your central data repository. It’s a distributed NoSQL database designed for high performance and scalability[2]. This is where all your application data will be stored and managed at the server level.

Other Couchbase Products (For Context)

  • Couchbase Edge Server: A lightweight database for resource-constrained edge environments, released in March 2025. It’s designed for edge deployments with limited resources[4][10].
  • Couchbase Capella: A fully managed Database-as-a-Service offering in the cloud[9].

Recommended Architecture for Your Use Case

Based on your requirements, here’s the architecture you should implement:

  1. Flutter App with Couchbase Lite: For local data storage and offline capabilities
  2. Sync Gateway: For synchronization and user-based access control
  3. Couchbase Server: As your central database
  4. Firebase Authentication: For user identity and authentication

Implementation Steps

1. Setting Up the Server Side with Docker

Fortunately, both Couchbase Server and Sync Gateway are available as Docker images, making deployment straightforward.

You can use Docker Compose to set up both services together. Here’s a simplified example:

version: '3'
services:
  couchbase-server:
    image: couchbase
    ports:
      - "8091-8096:8091-8096"
      - "11210-11211:11210-11211"
    volumes:
      - couchbase-data:/opt/couchbase/var

  sync-gateway:
    image: couchbase/sync-gateway
    ports:
      - "4984:4984"  # Public REST API
      - "4985:4985"  # Admin REST API
    depends_on:
      - couchbase-server
    volumes:
      - ./sync-gateway-config.json:/etc/sync_gateway/config.json

volumes:
  couchbase-data:

After launching the containers, you’ll need to:

  1. Initialize Couchbase Server through its web admin UI (http://localhost:8091)
  2. Create a bucket for your application data
  3. Create a Sync Gateway user with appropriate permissions[2]

2. Configuring Sync Gateway for Firebase Authentication

For Firebase Authentication integration, you’ll need to configure Sync Gateway to validate Firebase ID tokens. This involves:

  1. Setting up security definitions in your Sync Gateway configuration to accept Firebase tokens:

Here’s a sample configuration for Sync Gateway that incorporates Firebase authentication:

{
  "interface": ":4984",
  "log": ["*"],
  "databases": {
    "my-app-db": {
      "server": "http://couchbase-server:8091",
      "bucket": "my-app-bucket",
      "username": "sync_gateway",
      "password": "password",
      "users": {
        "GUEST": {"disabled": true}
      },
      "oidc": {
        "providers": {
          "firebase": {
            "issuer": "https://securetoken.google.com/YOUR-FIREBASE-PROJECT-ID",
            "client_id": "YOUR-FIREBASE-PROJECT-ID",
            "register": true
          }
        }
      },
      "sync": `function(doc, oldDoc) {
        if (doc._deleted) {
          return;
        }
        
        // Get the user ID from the document
        var userId = doc.owner;
        
        // If the document has an owner field, assign it to a channel with that user's ID
        if (userId) {
          channel("user." + userId);
        }
        
        // Public channel for shared documents
        if (doc.public) {
          channel("public");
        }
      }`
    }
  }
}

This configuration sets up Firebase as an OIDC provider and defines a sync function that assigns documents to channels based on the document’s owner field[14][6].

3. Setting Up the Flutter App with Couchbase Lite

To use Couchbase Lite in your Flutter app:

  1. Add the required packages:
flutter pub add cbl cbl_flutter
  1. Add either the Community or Enterprise edition:
flutter pub add cbl_flutter_ce  # Community Edition

or

flutter pub add cbl_flutter_ee  # Enterprise Edition
  1. Initialize Couchbase Lite in your app:
import 'package:cbl_flutter/cbl_flutter.dart';

Future<void> main() async {
  // Initialize Flutter binding
  WidgetsFlutterBinding.ensureInitialized();
  
  // Initialize Couchbase Lite
  await CouchbaseLiteFlutter.init();
  
  runApp(MyApp());
}
  1. Create and open a database:
import 'package:cbl/cbl.dart';

Future<void> setupDatabase() async {
  // Open the database (creating it if it doesn't exist)
  final database = await Database.openAsync('my-app-db');
  
  // Create a collection, or return it if it already exists
  final collection = await database.createCollection('documents');
}

4. Implementing Firebase Authentication and Replication

To implement synchronization based on Firebase user identity:

  1. Authenticate with Firebase:
import 'package:firebase_auth/firebase_auth.dart';

Future<User?> signInWithFirebase(String email, String password) async {
  UserCredential result = await FirebaseAuth.instance.signInWithEmailAndPassword(
    email: email,
    password: password,
  );
  return result.user;
}
  1. Set up replication with Firebase token:
import 'package:cbl/cbl.dart';

Future<void> setupReplication(Database database, String firebaseToken, String userId) async {
  // Create replicator configuration
  final targetEndpoint = UrlEndpoint(
    Uri.parse('ws://your-sync-gateway:4984/my-app-db')
  );
  
  final config = ReplicatorConfiguration(
    database: database,
    target: targetEndpoint,
    continuous: true,
    type: ReplicatorType.pushAndPull,
  );
  
  // Add Firebase token as authentication
  config.authenticator = HeaderAuthenticator(
    credentials: {'Authorization': 'Bearer $firebaseToken'}
  );
  
  // Set channels to pull only user's data
  config.channels = ['user.$userId', 'public'];
  
  // Create and start replicator
  final replicator = Replicator(config);
  replicator.addChangeListener((change) {
    print('Replication status: ${change.status.activity}');
  });
  
  replicator.start();
}
  1. To get the Firebase token:
String? token = await FirebaseAuth.instance.currentUser?.getIdToken();

Using Channels for User-Based Data Access

Sync Gateway’s channels feature is crucial for implementing user-based data access control[12]. In the configuration above:

  1. Documents are assigned to user-specific channels (user.{userId})
  2. When a user authenticates, they’re granted access only to their channels
  3. The replicator configuration limits syncing to only the user’s channels and shared public data

This ensures that users only download and access their own data, plus any shared data you designate as public.

Key Benefits of This Architecture

  1. Offline-First Experience: Users can work with data even without an internet connection
  2. Efficient Synchronization: Only relevant data is synced to each device
  3. Secure Authentication: Leverages Firebase’s robust authentication system
  4. Scalable Backend: Couchbase Server can scale to handle growing data needs
  5. Simplified Deployment: Docker makes deployment straightforward

Conclusion

By combining Couchbase Lite, Sync Gateway, Couchbase Server, and Firebase Authentication, you can build a robust offline-first Flutter application with secure, user-based data synchronization. The architecture outlined above provides a solid foundation for your application, leveraging Docker for simplified deployment.

For your specific requirements, you’ll need Couchbase Server and Sync Gateway on the backend, with the cbl and cbl_flutter packages in your Flutter app. This combination will provide the offline capabilities and synchronization features you need while integrating with Firebase Authentication for user identity.

Sources
[1] Install | Couchbase Lite for Dart & Flutter Install | Couchbase Lite for Dart & Flutter
[2] docker/compose/couchbase-server-sync-gateway/README.md at … docker/compose/couchbase-server-sync-gateway/README.md at master · couchbase/docker · GitHub
[3] Sync Gateway: Secure Data Access & Synchronization for Edge Apps Sync Gateway: Secure Data Access & Synchronization for Edge Apps
[4] The Offline-First Database for the Resource Constrained Edge Meet Couchbase Edge Server: The Offline-First Database for the Resource Constrained Edge - The Couchbase Blog
[5] Best Practices for Anonymous Authentication - The Firebase Blog Best Practices for Anonymous Authentication
[6] Using Firebase to authenticate users | API Gateway Documentation Using Firebase to authenticate users  |  API Gateway Documentation  |  Google Cloud
[7] cbl | Dart package - Pub.dev cbl | Dart package
[8] docker/community/sync-gateway/1.2.0/README.md at … - GitHub docker/community/sync-gateway/1.2.0/README.md at master · couchbase/docker · GitHub
[9] Data Sync between Capella App Services and Mobile Deployments Data Sync between Capella App Services and Mobile Deployments
[10] Couchbase Unveils Edge Server to Help Organizations Solve Real … Couchbase Unveils Edge Server to Help Organizations Solve Real-World Edge Application Challenges
[11] Manage Users in Firebase - Google Manage Users in Firebase
[12] Channels | Couchbase Docs Channels | Couchbase Docs
[13] Couchbase Lite sync with Firebase Database Couchbase Lite sync with Firebase Database - Couchbase Lite - Couchbase Forums
[14] How to use firebase authentication in couchbase sync gateway android - How to use firebase authentication in couchbase sync gateway - Stack Overflow
[15] Manage live & preview channels, releases, and versions for your site https://firebase.google.com/docs/hosting/manage-hosting-resources
[16] cbl_flutter example | Flutter package - Pub.dev cbl_flutter example | Flutter package
[17] Set up Sync Gateway for use with Inventory Demo App Developer Portal | Couchbase
[18] Capella Couchbase Server vs Sync Gateway vs Couchbase Lite Capella Couchbase Server vs Sync Gateway vs Couchbase Lite - Couchbase Lite - Couchbase Forums
[19] Lightweight, Offline-First Database Server | Couchbase Edge Server Lightweight, Offline-First Database Server | Couchbase Edge Server
[20] Couchbase Lite for Dart https://cbl-dart.dev
[21] SYNC gateway couldn’t connect to couchbase server in a docker … SYNC gateway couldn't connect to couchbase server in a docker environment - Stack Overflow
[22] Whats the difference between couchbase capella … - Stack Overflow Whats the difference between couchbase capella vs couchbase server? - Stack Overflow
[23] Couchbase Unveils Edge Server to Help Organizations Solve Real … Couchbase Launches Edge Server: Run Full Database Functions on 1GB RAM Devices | BASE Stock News
[24] cbl-dart/cbl_counter: Simple Flutter app which uses Couchbase Lite … GitHub - cbl-dart/cbl_counter: Simple Flutter app which uses Couchbase Lite to store, observe and replicate a counter.
[25] couchbase/sync-gateway - Docker Image https://hub.docker.com/r/couchbase/sync-gateway
[26] Sync Gateway and Cross Data Center Replication - Couchbase Disaster Recovery with Couchbase Mobile - Sync Gateway and Cross Data Center Replication - The Couchbase Blog
[27] Couchbase Unveils Edge Server to Help Organizations Solve Real … Couchbase Unveils Edge Server to Help Organizations Solve Real-World Edge Application Challenges
[28] Firebase alternatives for Data Storage and Data Sync - ObjectBox Firebase alternatives for Data Storage and Data Sync
[29] Using Firebase Authentication - FlutterFire Using Firebase Authentication | FlutterFire
[30] Are indefinitely growing channels a problem (sync gateway) Are indefinitely growing channels a problem (sync gateway) - Sync Gateway - Couchbase Forums
[31] Compare Couchbase Mobile vs. Google Firebase Couchbase Mobile vs. Google Firebase
[32] Firebase Authentication Firebase Authentication
[33] How to use firebase authentication in couchbase sync gateway https://www.youtube.com/watch?v=DxTAr0RdDro
[34] Realtime integration (Firebase, Socket.io) - DreamFactory Forum Realtime integration (Firebase, Socket.io) - Server-Side Scripting - DreamFactory Forum
[35] Sign in - Google Accounts https://console.firebase.google.com
[36] Sync Gateway “Channels” in PouchDB - couchbase - Stack Overflow couchbase - Sync Gateway "Channels" in PouchDB - Stack Overflow
[37] Firebase and Couchbase usage — Feel the Difference - Rozdoum Firebase and Couchbase usage — Feel the Difference
[38] Firebase rules for secure access without sign-in? Firebase rules for secure access without sign-in? - Questions about Thunkable - Community
[39] Firebase Auth Tutorial #15- Firestore Users Collection - YouTube https://www.youtube.com/watch?v=qWy9ylc3f9U

The community has flagged this post as SPAM

Ok. Sorry for that.

The community has flagged this post as SPAM

Ok. Sorry for that.

What happenings here?

I was sharing research in configuring and using Couchbase Lite for Flutter offline-first database approach.

The post was flagged by the community as spam, so, it doesn’t make sense to continue.