Connecting Couchbase Lite database to Sync Gateway

This article explains how to get your mobile app’s Couchbase Lite documents / data pushed and pulled to a remote end point using the sessions-based mechanism.

There are two things to be done in the mobile app: one is to create the methods to communicate with your authentication server in order to create users in the gateway and get his session keys (if you didn’t already, this is explained in the article: Configuring your own Couchbase Mobile sync backend). The other is to provide this received session key for the Couchbase Lite SDK for replication.

Following is a sample workflow with user interaction:


“WebApp” represents a Custom Auth Service. The custom auth server only proceeds to calling the gateway’s user administration API (POST _session) after checking if the user-provided credentials are correct.

We are now concerned with the interactions involving the “App”, and “Couchbase Lite” in the diagram. Once you have the session key in your mobile app, proceed to setting up replication:


Getting your first replication running

For this, we have a class named “CBLReplication”. From the documentation:

A Replication object represents a replication (or “sync”) task that transfers changes between a local database and a remote one. To replicate, you first get a new Replication object from a Database, then configure its settings, then tell it to start. The actual replication runs asynchronously on a background thread; you can monitor its progress by observing notifications posted by the Replication object when its state changes, as well as notifications posted by the database when documents are changed by the replicator.

Activating the “secure” parameter of the CBLReplication setCookie’s method simply specifies that the session cookie should only be sent over a secured connection (SSL/TLS).

Finally, the complete app architecture can be drawn like this (note the added CBLReplication):




You have now the possibility to replicate documents to a server and work offline. There is one critical point where the app must be online/connected to the auth server in order to bootstrap the syncing process, and that is that of the login: in order to assign the proper ownership to documents. After that, it can operate offline and changes will get synced when a connection is established.

Note: First workflow picture was obtained from Couchbase Mobile’s google groups.