I believe pouchdb-authentication is a complication[1], and there are known issues regarding that plugin[2,3].
I am of the opinion using Basic Authentication over HTTPS is best for most use cases. I see pouchdb-authentication being handy in cases where there is a need to switch credentials often to perform various tasks.
The below code demonstrates different ways to authenticate. This code works with nodejs but is easily adapted for the browser, assuming server side CORS is setup correctly[4].
let PouchDB = require("pouchdb");
PouchDB.plugin(require("pouchdb-find"));
PouchDB.plugin(require("pouchdb-authentication"));
const testUrlTemplate = "http://*127.0.0.1:5984/test";
const doTask = async (db) => {
await db.createIndex({
index: { fields: ["area"] },
});
return await db.find({
selector: { area: { $gt: null } },
fields: ["_id", "area"],
sort: ["area"],
});
};
// connect to remote db using basic auth (preferred with https)
const basicAuth = async (credentials) => {
const url = testUrlTemplate.replace("*", "");
return new PouchDB(url, {
skip_setup: true,
auth: credentials,
});
};
// connect to remote db using unwise cleartext
const unwiseUrl = async (credentials) => {
const url = testUrlTemplate.replace(
"*",
`${credentials.username}:${credentials.password}@`
);
return new PouchDB(url, {
skip_setup: true,
});
};
// convenience.
const log = (obj) => {
console.log(JSON.stringify(obj));
};
(async () => {
try {
const credentials = {
username: "some_user",
password: "some_password",
};
let db = await basicAuth(credentials);
let result = await doTask(db);
log(result);
db = await unwiseUrl(credentials);
result = await doTask(db);
log(result);
// use basic auth the init the db, then switch to another user
// with a cookie session.
db = await basicAuth(credentials);
await db.logIn("plain_user", "plaintext_password");
result = await doTask(db);
log(result);
} catch (err) {
// oopsy
log(result);
}
})();
Do note I altered your find code, as the sort parameter would break the query.
1PouchDB Security
2pouchdb-authentication issue #243
3pouchdb-authentication issue #204
4Add CORS to CouchDB