Database on the browser with PouchDB



March 29, 2021

alt text

What is PouchDB and how to use it?

Hey guys, what's up? Today we'll be taking a look at PouchDB - a JavaScript database that runs within the browser! This can be super handy for specific scenarios as it gives you a way to store some data on the client, without needing any backend work!

So let's take a look at how we can use it. The first step is to include pouchdb js file in your HTML with a script tag. Now, we can go ahead and start using PouchDB!

<h2>Users on database</h2> <div id="users"></div> <!-- ... --> <script src=""></script>

Take a look at the script I provided to see how we can easily create a database for 'users' and start adding and retrieving these users.

var db = new PouchDB('users') var usersDiv = document.getElementById('users') const addUser = (id, name, email) => { const user = { _id: id, name, email, } db.put(user, (err, res) => { if (err) { console.log('Error', err) } if (res) { console.log('User created!', res) } }) } const showUsers = () => { db.allDocs({ include_docs: true, descending: true }, (err, doc) => { if (err) { console.log('Error', err) } if (doc) { => { const nameEl = document.createElement('p') const emailEl = document.createElement('p') const divEl = document.createElement('div') divEl.classList.add('single-user') nameEl.innerHTML = emailEl.innerHTML = divEl.appendChild(nameEl) divEl.appendChild(emailEl) usersDiv.appendChild(divEl) }) } }) } addUser('16232', 'John McKenzie', '') addUser('12312', 'Erik Garner', '') addUser('16250', 'Anthony Cuban', '') showUsers()

Obviously, this shouldn't be used to store huge amounts of data since this will use the user's disk for storage. But still, this can be really handy for smaller sets of data!

How about you? Have you ever used PouchDB? What's your thoughts on having a database in the browser?