Easy offline-first mobile and desktop web apps with PouchDB

776 views

Published on

Offline-first web application development leads to faster apps and a better user experience, but is it realistic? It's hard enough to think about "mobile-first". And what if your code needs to run on a smart phone, in a browser, and as an installed desktop application? Do you really have time to implement "offline-first" for all these platforms and their variants? Thanks to a combination of open source packages including PouchDB, React, and Electron, it's now possible to write one offline-first web application that runs everywhere.

Published in: Software
  • Be the first to comment

  • Be the first to like this

Easy offline-first mobile and desktop web apps with PouchDB

  1. 1. 1© 2015 Rogue Wave Software, Inc. All Rights Reserved. 1 Easy offline-first mobile and desktop web apps with PouchDB Rod Cope, CTO
  2. 2. JFTPNT (5/15) AKC Event Operations – Performance Events PO Box 900051 Raleigh, NC 27675-9051 Tel 919 816-3908 Fax 919 816-4211 www.akc.org Event #____________________ STAKE____________________________ No. of Entries ______________ Date(s) on which stake was Judged _________________________ No. of Starters _____________ AWARDS: Name of Dog ______________________________________________ Breed____________________ DOB _________________ Sex_____ AKC ® No. _______________________________________ Sire ________________________________ Dam _____ __________________ Owner’s Name______________________________________________ Owner's Address________________________________________ Handler’s Name___________________________________________ Name of Dog ______________________________________________ Breed____________________ DOB _________________ Sex_____ AKC ® No. _______________________________________ Sire ________________________________ Dam _____ __________________ Owner’s Name______________________________________________ Owner's Address________________________________________ Handler’s Name___________________________________________ Name of Dog ______________________________________________ Breed____________________ DOB _________________ Sex_____ AKC ® No. _______________________________________ Sire ________________________________ Dam _____ __________________ Owner’s Name______________________________________________ Owner's Address________________________________________ Handler’s Name___________________________________________ Name of Dog ______________________________________________ Breed____________________ DOB _________________ Sex_____ AKC ® No. _______________________________________ Sire ________________________________ Dam _____ __________________ Owner’s Name______________________________________________ Owner's Address________________________________________ Handler’s Name___________________________________________ Note: Field Trial Secretary shall list on the back of this page the registered name and number of each dog given a Judge's Award of Merit JUDGE’S CERTIFICATION We certify that the above awards are in accord with our judging of the stake and that the Judges' Award of Merit as noted on the back of this page are correct. ____________________________________________ _______________________________________________ (Judge’s Signature) (Judge’s Signature) (Print Judge's Name) (Print Judge's Name) FIELD TRIAL SECRETARY'S CERTIFICATION I certify that the judges have verified the awards and signed this page. I certify that there were ___________ENTRIES and ____________ STARTERS in this stake. DATE Signature of Field Trial Secretary PLEASE GIVE THE NUMBER OF EACH BREED STARTED: POINTING BREED FIELD TRIAL REPORT PAGE 1st 2nd 3rd 4th       AKC® HUNTING TESTS FOR POINTING BREEDS   Use separate sheets for Junior, Senior and Master levels and additional sheets if needed. NOTE: Score Juniors in Hunting, Bird Finding, Pointing and Trainability only; score Seniors and Masters in all categories.   CIRCLE ONE – (JUNIOR / JUNIOR ADVANCED SENIOR / SENIOR ADVANCED MASTER / MASTER ADVANCED)     BRACE #   DOG’S NAME   BREED   HANDLER   HUNTING BIRD FINDING ABILITY   POINTING   TRAINABILITY RETRIEVING (NOT APPLICABLE IN JUNIOR) HONORING (NOT APPLICABLE IN JUNIOR)   TOTAL   AVERAGE                                                                                                                                                                                                   In order to receive a Qualifying score, a dog must acquire a minimum of not less than 5 on each of the categories of abilities (4 categories in Junior; 6 categories in Senior and Master) with an overall average score of not less than 7.0. “Advanced” titles require an overall average of not less than 8.0. When averaging scores, divide total in Junior by 4; divide total in Senior and Master by 6. Judges must agree on which dogs will qualify and will not qualify.         JHTPNT (4/15) Offic i al American Kennel Club® FIELD TRIAL or HUNT TEST Entry Form AKC Rules, Regulations, Policies and Guidelines are available on the American Kennel Club website: www.akc.org AGREEMENT IcertifythatIamtheactualownerofthedog,orthatIamthedulyauthorizedagentoftheactualownerwhosenameIhaveenteredabove.Inconsiderationoftheacceptanceofthisentry,I(we) agreetoabidebytherulesandregulationsofTheAmericanKennelClubineffectatthetimeofthisevent,andanyadditionalrulesandregulationsappearinginthepremiumlistofthiseventand entryformandanydecisionmadeinaccordwiththem.I(we)agreethattheclubholdingthiseventhastherighttorefusethisentryforcausewhichtheclubshalldeemsufficient.I(we)certifyand representthatthedogenteredisnotahazardtopersonsorotherdogs.Inconsiderationoftheacceptanceofthisentryandoftheholdingofthiseventandoftheopportunitytohavethedogjudged andtowinprizes,ribbons,ortrophies,I(we)agreetoholdtheAKC,theevent-givingclub,theirmembers,directors,governors,office rs, agents,superintendentsoreventsecretaryandtheowner and/or lessor of the premises and any provider of services that are necessary to hold this event and any employees or volunteers of the aforementioned parties, and anyAKC approved judge, judgingatthisevent,harmlessfromanyclaimforlossorinjurywhichmaybeallegedtohavebeencauseddirectlyorindirectlytoanypersonorthingbytheactofthisdogwhileinorabouttheevent premisesorgroundsornearanyentrancethereto,andI(we)personallyassumeallresponsibilityandliabilityforanysuchclaim;andI(we)furtheragreetoholdtheaforementionedpartiesharmless from any claim for loss,injury or damage to this dog.Additionally,I (we) hereby assumethe sole responsibility for and agree to indemnify,defend and save theaforementioned parties harmless fromanyandalllossandexpense(includinglegalfees)byreasonoftheliabilityimposedbylawuponanyoftheaforementionedpartiesfordamagebecauseofbodilyinjuries,includingdeathat any time resulting therefrom,sustainedby any personor persons, including myself(ourselves),or on account ofdamage to property, arising outofor in consequenceofmy (our)participationin thisevent,howeversuch,injuries,deathorpropertydamagemaybecaused,andwhetherornotthesamemayhavebeencausedormaybeallegedtohavebeencausedbythenegligenceof theaforementionedpartiesoranyoftheiremployees,agents,oranyotherperson.I(we)agreethatthedeterminationofwhethertheinjuryisseriousshallbemadebytheeventveterinarianand isbindingonme(us). I (WE) AGREE THAT ANY CAUSE OF ACTION, CONTROVERSY OR CLAIM ARISING OUT OF OR RELATED TO THE ENTRY, EXHIBITION OR ATTENDANCE AT THE EVENT BETWEEN THE AKC AND THE EVENT-GIVING CLUB (UNLESS OTHERWISE STATED IN THIS PREMIUM LIST) AND MYSELF (OURSELVES) OR AS TO THE CONSTRUCTION, INTERPRETATION AND EFFECT OF THIS AGREEMENT SHALL BE SETTLED BY ARBITRATION PURSUANT TO THE APPLICABLE RULES OF THE AMERICAN ARBITRATION ASSOCIATION. HOWEVER, PRIOR TO ARBITRATION ALL APPLICABLE AKC BYLAWS, RULES, REGULATIONS AND PROCEDURES MUST FIRST BE FOLLOWED AS SET FORTH IN THE AKC CHARTER AND BYLAWS, RULES, REGULATIONS, Club: Location: Email:Tel: Signature of owner or his agent duly authorized to make this entry: Full Name Breed: Sire: Actual Owner(s): Owner’s Address: Event #:Date(s): Event type (test or trial): I enclose entry fees in the amount of: $ Date of Birth:Sex: Enter in Stake/Test: Call Name: Dam: Name of Breeder: Name of Owner’s Agent/Handler: AKC® No. Foreign & List Country: Beagle Trials ONLY: Male Female Retriever Trials ONLY this dog is qualifie d for (check answe r ): Limited All-Age Stake: YES NO Restricted All-Age Stake: YES NO SpecialAll-Age Stake: YES NO 13” Class 15” Class AFN999 (03/16) v1.1 Edit City: State: Zip: Name of Jr. Handler (if any): Jr. Handler #:
  3. 3. Dog event administration on-site • Change, cancel, or add runs – May take payment or provide refunds • Record results – Pass/fail, scores – Must be mailed to AKC after event is finished
  4. 4. My use case: replace paper forms • Devices: laptops, some tablets and phones • Challenges – Little or no Internet access – Users are NOT technical • Most are 50-75 years old • Copy/paste is hard • Don’t understand “synchronization”
  5. 5. Offline-first • Offline!
  6. 6. Offline-first • Latency – Multiple round trips
  7. 7. Offline-first • Offline! • Latency – Multiple round trips • WiFi – Bad/slow connection Your site name here
  8. 8. Offline-first • Offline! • Latency – Multiple round trips • WiFi LieFi – Bad/slow connection Your site name here use an offline-first app!
  9. 9. Synchronization options
  10. 10. Offline-first challenges • User experience • Security • Data management
  11. 11. Offline-first challenges • User experience • Security • Data management
  12. 12. User experience (UX) • Implications of offline-first: – No “make this available offline” – Internet access is a feature – Usually sync data eventually
  13. 13. User experience (cont.) • Users don’t understand online/offline/sync – Getting a ”web” page means “online” – Automatic and seamless sync • Remind users to sync – Online-only features • Indicate online status
  14. 14. UX: Online/offline indicators https://github.com/hubspot/offline Make sure you need them!
  15. 15. Offline-first challenges • User experience • Security • Data management
  16. 16. Security: authentication/authorization • Online client – Must be online first – Auth with server, store login token • Offline client – Local auth – Assume all users are admins • Back online client – Auth with stored token – Bi-directional synchronization of changes
  17. 17. Online security flow
  18. 18. Offline security flow • Local authentication (optional) – Password, token, device-specific, OS, 2FA • Local authorization (optional) • Can’t prevent authentication/authorization – User has physical control of device – Don’t store sensitive server data • No private server passwords, keys, tokens!
  19. 19. Security: offline changes • Save changes to local storage • Prevent online-only changes
  20. 20. Security: offline changes (cont.) • Server can’t trust offline changes – Never trust user input in any form – Authenticate and authorize – Validate and normalize data • Data format migration • Apply accepted changes to master data store • Communicate results back to client
  21. 21. Back online security and data flow
  22. 22. Offline-first challenges • User experience • Security • Data management
  23. 23. Data: offline queries – Okay to query client-side cache • Example: show user profile and preferences – Inform user if data may be missing • Example: event search results
  24. 24. Data: offline changes (mutations) • User-private or “lightly shared” data – Create transactions & prepare for submission • Example: shopping, enter dog event results – Inventory or dynamic pricing might be a problem
  25. 25. Data: e-commerce example
  26. 26. Data: offline changes (mutations) • Shared data – Admin can change price or description – Can resolve conflicts automatically • Example: sequence number, date, user id – May need user to resolve conflicts • Example: Original price: 10 Your price: 11 Other price: 12 Make new price 11 Make new price 12
  27. 27. Data: offline and online • Offline – Save all changes on the client • Online – Still save changes on the client first – Bi-directional sync with the server – Conflict detection & resolution
  28. 28. Offline data options: AJAX • The default option: retry or show error • Complex logic to retry failed REST calls • 5xx errors, timeouts, network errors • User closes browser/tab, browser crash, machine crash – What state is the transaction in if the browser tab hangs or the browser crashes after the user clicks “Purchase”? • Probably bad user experience • Definitely bad developer experience!
  29. 29. Pyramid of Doom
  30. 30. Promises • It’s better with promises, but… – 5xx errors, timeout, network error, user closes browser/tab, browser crash, machine crash • What state is the transaction in if the browser tab hangs or the browser crashes after the user clicks “Purchase”?
  31. 31. Offline implementation options
  32. 32. Progressive Web Apps
  33. 33. Offline data options: SW and PWA • Service Workers and Progressive Web Apps • JavaScript-based proxy between your client-side code and the browser • Good for caching patterns and offline support • No support today in Safari/iOS Safari, IE/Edge • “In development” for Edge • “Under consideration” for WebKit (Safari) • Powerful option for the future, but not ready today unless your audience only uses Chrome or Firefox
  34. 34. Offline data options: PouchDB! • JavaScript, Apache 2.0 license • “The database that syncs!” • Replicates with PouchDB or CouchDB – Local or remote – Uni- or bi-directional (master-master) – Automatic conflict resolution – HTTP (easy testing with curl)
  35. 35. Offline data options: PouchDB (cont.) • Change stream – Observe add/change and delete • Backing stores – Browser: IndexedDB, WebSQL, memory – Node.js: options below, memory, and more
  36. 36. PouchDB platforms
  37. 37. Web app languages
  38. 38. Web app frameworks
  39. 39. Desktop apps
  40. 40. Desktop apps… with web technology!
  41. 41. React desktop – Mac and Windows
  42. 42. Key packages Client • React, React Native, React Desktop + Electron • Redux – Maintains client state • GraphQL/Apollo Client (optional) • PouchDB Server • Express • GraphQL/Apollo Server (optional) • node.js • PouchDB or CouchDB
  43. 43. Client: React and friends for UI • React for responsive web app • React Native for native mobile UI • React Desktop for native-looking desktop UI • React Router for URL management
  44. 44. Client: React and friends for data • Redux for client state management • Redux/PouchDB – Bi-directional state sync with local database • Pouch Websocket Sync – Bi-directional sync: local/remote DB’s • PouchDB – Uses IndexedDB or WebSQL in browser • Optional: GraphQL integration with PouchDB
  45. 45. PouchDBRedux Server PouchDB/ CouchDB
  46. 46. Server: React, PouchDB, and friends •React SSR (Server-Side Rendering) –Include initial Redux store state •Pouch Websocket Sync for sync with auth & reconnect •PouchDB on LevelDB (from Google) –Could also use CouchDB, Cloudant, Couchbase •Pouch Clerk for (async) transaction state machine
  47. 47. http://blog.yld.io/2016/06/24/how-to-build-a-reliable-transaction-experience-for-your-customers
  48. 48. Server (continued) • Don’t have to use PouchDB/CouchDB on server • Example: my app is based on Meteor and MongoDB – PouchDB synced with MongoDB on server – Pouch Clerk calls Meteor method which updates MongoDB – Pouch Clerk updates PouchDB with results – One server-side PouchDB per dog event
  49. 49. Conclusions • Offline-first leads to a better user experience • PouchDB enables offline-first – Runs everywhere – Synchronization with conflict resolution • Build web, mobile, and even desktop apps with one architecture, language, and framework family – JavaScript, React, Electron
  50. 50. Questions?
  51. 51. Rod Cope, CTO Rogue Wave Software
  52. 52. 68© 2015 Rogue Wave Software, Inc. All Rights Reserved. 68

×