neighbourhoodie-nnh-logo

PouchDB Tip: Use CouchDB as an API posted Wednesday, October 16, 2024 by The Neighbourhoodie Team

PouchDB and CouchDB used together are a powerful combination and one of the very few technologies that allow you to build truly robust offline web applications.

This little tip however is for when in addition to having your core data model available offline, you need a normal web server API to store or retrieve some other information.

Say your app is collecting vital signs of your orchard. You want to track how many apples are on the tree, how much water was given, when was the last time your tree got a health check up, the usual orchard stuff.

Of course your app uses PouchDB in the browser, so you can see all data when you are out and about, and so that you can take measurements right away instead of putting them on a piece of paper first.

Once you’re done with your inspection round and you’re back in your office, you still use the same app to get an overview of how your orchard is doing, this time on your computer and not your phone.

From the measurements that have come in you can predict that your stock of fertiliser is going to run out soon, so you need to place an order. Instead of building a specialised API that only accepts orders, you can use PouchDB to access CouchDB remotely and use a CouchDB database as an API.

Your client is already authenticated with the backend, access control is sorted out, so there is nothing stopping you from just getting your job done here.

In PouchDB you can access local databases like so:

const db = new PouchDB('orchard')

But you can also access remote databases:

const db = new PouchDB('https://example.com/orchard')

That way, you can save yourself building another component on your server side, just use CouchDB as an API.