'Dexie pass auth token with request

My app lets guests (not logged in) save their data in the indexeddb. When logged in this data should be synced with a backend.

I implemented dexie for the handling of the indexeddb and dexie syncable for the sync part together with websocket (as in the dexie examples) for now. Currently my plan is NOT to use dexie cloud.

In the backend I want to verify the user (jwt bearer token) before doing things and store data i.e. related to the user and only send his/her data back and not everything.

As far as I can tell, passing the auth token should be handled inside the websocket connection and I guess right now I am opting to send it along within messages --> Let me know if there is a better way.

A message would look like this (see the token):

            ws.send(JSON.stringify({
                token,
                type: 'changes',
                changes: changes,
                partial: partial,
                baseRevision: baseRevision,
                requestId: requestId
            }));

My attempts: Calling this.syncable.connect with the token as an option based on auth events. When the user logs in then with a token, when the user logs out then without.

This results in multiple websocket sync connections and following messages are sent multiple times hence.

Then I thought calling this.syncable.disconnect(url) before would solve this but this doesnt show any difference for me. Even as I did a loop over this.syncable.list().

Calling this.syncable.delete() if I understand it correctly should not be used.

Afterwards I thought I could pass a tokenFactory via the options to this.syncable.connect so that inside the sync-protocoll I could call it to get the current token:

const token = await options.getToken();

But when I do this, I get a dexie error and the connect fails.

"Failed to execute 'add' on 'IDBObjectStore': () => (0,rxjs__WEBPACK_IMPORTED_MODULE_6__.lastValueFrom)(this.state.token$) could not be cloned.

DataCloneError: Failed to execute 'add' on 'IDBObjectStore': () => (0,rxjs__WEBPACK_IMPORTED_MODULE_6__.lastValueFrom)(this.state.token$) could not be cloned."

So how could I achieve what I want -> passing the auth token? What is the best way to do this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source