Offline-first web-app using PouchDB, Cloudant and Firebase

What is a CouchDB-based server

PouchDB is based on Apache CouchDB, and CouchDB killer feature is the ability to replicate. Two-way replication (sync) is a breeze.

Data structure

For easily synchronize browser data to server, we’re gonna have a database for each user, and only that user will have privileges to read and write on it.

Authentication and Authorization

Firebase is going to be our auth service. For authorization we could use the default security system from CouchDB or Cloudant credentials. In this example I’m gonna use Cloudant’s.

Authentication and authorization flow

Authentication and authorization diagram
  • Cloud Functions for Firebase onCreate event triggers:
  • —Create a new database on Cloudant
  • — Create a credential for that user
  • — Set the privileges for that credential on the newly created database
  • — Save key on Firebase/Firestore (if you’re using CouchDB security system, you could save it on _usersdoc).
  • That’s it you have everything to sync user’s data.

Let’s Sync

Setting up Cloudant

First thing we do is create a Cloudant service on IBM Cloud, remember to select “IAM and legacy credentials” on “Authentication method”.

{
"apikey": "KEY",
"host": "USER.cloudantnosqldb.appdomain.cloud",
"iam_apikey_description": "Auto-generated for key XXX",
"iam_apikey_name": "firebase-cloud-functions",
"iam_role_crn": "crn:v1:bluemix:public:iam::::serviceRole:Manager",
"iam_serviceid_crn": "crn:v1:bluemix:public:iam-identity::a/XXX",
"password": "PASSWORD",
"port": 443,
"url": "https://KEY:PASSWORD@USER.cloudantnosqldb.appdomain.cloud",
"username": "USER"
}

Very simple PouchDB example

PouchDB sync in action

Setting up Cloud Functions

  1. Install firebase-tools globally
  2. Log in
  3. Start a cloud functions project
  4. Install dependencies
npm install -g firebase-tools
firebase login
firebase init functions
npm install
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId}/{document=**} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}

That’s it

From now on, you should implement the authentication steps from Firebase, and learn to love PouchDB!

Possible improvements

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store