4

I have a local RxDB database and I want to connect it with CouchDB. Everything seems to works fine except for authentication. I have no idea how to add it differently then inserting credentials in database url:

database.tasks.sync({
        remote: `http://${username}:${pass}@127.0.0.1:5984/tododb`,
      });

I would like to use JWT auth but can't find how to add a token to sync request. I found only some solutions for PouchDB (pouchdb-authentication plugin) but can't get it working with RxDB.

micnil
  • 4,705
  • 2
  • 28
  • 39
Alan Wołejko
  • 442
  • 2
  • 5
  • 20
  • A fairly broad question. I've always used header auth (i.e. basic) over HTTPS, which is secure enough for my cases. Have you read over [CouchDB's Authentication docs](https://docs.couchdb.org/en/stable/api/server/authn.html#authentication)? – RamblinRose Jun 01 '20 at 14:14
  • Yes, I read it but I mean - don't know how to add anything to RxDB request header. For base auth (my example from question) it's converted and added automatically but how can I add to this header cookie or JWT token? – Alan Wołejko Jun 01 '20 at 16:09

1 Answers1

5

RxDB is tightly coupled with PouchDB and uses its sync implementation under the hood. To my understanding, the only way to add custom headers to a remote PouchDB instance (which is what is created for you when you pass a url as the remote argument in sync), is to intercept the HTTP request:

var db = new PouchDB('http://example.com/dbname', {
  fetch: function (url, opts) {
    opts.headers.set('X-Some-Special-Header', 'foo');
    return PouchDB.fetch(url, opts);
  }
});

PouchDB replication documentation (sync) also states that:

The remoteDB can either be a string or a PouchDB object. If you have a fetch override on a remote database, you will want to use PouchDB objects instead of strings, so that the options are used.

Luckily, RxDB's Rx.Collection.sync does not only accept an server url as the remote argument, but also another RxCollection or a PouchDB-instance.

RxDB even reexport the internally used PouchDB module, so you do not have to install PouchDB as a direct dependency.

import { ..., PouchDB } from 'rxdb';

// ...


const remotePouch = new PouchDB('http://27.0.0.1:5984/tododb', {
  fetch: function (url, opts) {
    opts.headers.set('Authorization', `Bearer ${getYourJWTToken()}`)
    return PouchDB.fetch(url, opts);
  }
})

database.tasks.sync({
  remote: remotePouch,
});
micnil
  • 4,705
  • 2
  • 28
  • 39