Couchbase Sync Gateway Proxy in Node/Express

I recently worked on a offline-first Mobile app which uses Couchbase/Sync Gateway and AWS Lambda as a Backend and Ionic/Angular as a front-end. The Application is using PouchDB to store the data locally, sync later with server in case of network unavailability.

The app was using the standard Username/Password mechanism for the authentication and some features needed integration with 3rd party services like NodeBB and Amazon Alexa. So we decided to switch to OAuth based authentication and use Auth0 for the user management. Auth0 is a popular (and super-cool) cloud based identity provider service.

The PouchDB running on client side web/mobile app was using the Pouchdb-Authentication plugin which uses username/password to login with the Sync Gateway and create a sync link to push/pull data from Sync Gateway and local pouchdb.

As we don’t manage user password anymore, we decided to remove this part and instead control the communication via Token or Cookie (whichever is manageable)

After some trials and errors I end up writing a simple proxy, which utilises the Sync Gateway Admin API to create session for PouchDB and a redirect which routes all the PouchDB traffic to SG from the NodeJS.

This is how it works internally:

  • After successful auth0 authentication we will pass the JWT in each request
  • Before PouchDB connection is made, we will call the /sync/_signin/userID endpoint which creates an active Session in Sync Gateway and returns the generated cookie
  • The cookie will be set on the client side
  • PouchDB connection is made to the Proxy URL, /sync

The following is the NodeJS side of code having two main routes: 1) creates Session in SG via Admin port and 2) routes all the PouchDB requests to SG.

On client side we need to create PouchDB connection with remote URL. We don’t need to use username/password anymore and the requests will pass the Cookie we stored previously.