Using Web Browser's Indexed DB in SvelteKit

using-web-browsers-indexed-db-in-sveltekit-3oo3

Introduction

This blog post comes from my current project where i don't want a server side DB for user tracking or for any other purposes but still wanted to save things for the user. While doing some basic research I had to choose between localStorage & Indexed DB. Both have their own benefits and drawbacks but for my use case where i have to store data that might go above the localStorage allowed data size. when i started reading more about IndexedDB,I found dexie which is a wrapper around IndexedDB and it have to good api's for querying the IndexedDB. And One more thing, IndexedDB is supported in workers which is the best thing to have when you have client side data management.

Resources

Prerequisites

  • NodeJs with a package manager pnpm.
  • New or Existing SvelteKit project
  • Now install dexie
pnpm i dexie
Enter fullscreen mode Exit fullscreen mode

Setting up Dexie

I'm using Typescript and it's not mandatory to use ts.

  • Create a db.ts file in lib directory.
  • As I'm using typescript I have to provide interface for table.
export interface favorite {
    id: string;
    name: string;
    image: string;
    description: string;
    slug: string;
}
Enter fullscreen mode Exit fullscreen mode

So here i created a favorite interface with id, name, image, description and slug. These are going to table columns as well.

  • After deciding on table columns, we need to create an dexie instance but as we are using we have to do it little bit differently (for js you can directly initiate it).
import Dexie, { type Table } from 'dexie';


export class MyDexieExtension extends Dexie {

    favorite!: Table<favorite>;

    constructor() {
        super('myData.db');
        this.version(1).stores({
            favorite: '&id, name, image, description, slug',
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

Here, I have extended Dexie so we can use typescript autocomplete and things.

  • favorite!: Table<favorite>; Adds typescript supports for queries.

  • favorite: '&id, name, image, description, slug', here we have some special characters like & which define primary key and there are other characters like this to make things simple. Please check dexie docs for this.

  • After creating db what we need to do is query it and dexie have wast api's. Here, I'm going to show some basic one and last one is for svelte lovers.

    Note: Use browser specific api after checking for browser or onMount as IndexedDB is only available in browser.


import {db} from "$lib/db"

// Insert query
await db.favorite.add({
id: 'dfghg2334w',
name: 'The Ether',
image: 'url',
description: 'Web Dev'
slug: 'dfghg2334w-the-ether'
})

// Update Query
await db.favorite.put({
id: 'dfghg2334w',
name: 'Shivam Meena'
})

// Delete Query
await db.favorite.delete('dfghg2334w')

Enter fullscreen mode Exit fullscreen mode

As you can see how easy it is to query.

  • Ok ok, now comes the best part of svelte and dexie. Svelte have best stores in JS world and dexie provide something for us. The liveQuery:
<script>
  import { liveQuery } from "dexie";
  import { db } from "$lib/db";

  let favorites = liveQuery(
    () => db.favorite.toArray()
  );

</script>
<ul>
  {#if $favorites}
    {#each $favorites as favorite (favorite.id)}
      <li>{favorite.name}, {favorite.slug}</li>
    {/each}
  {/if}
</ul>

Enter fullscreen mode Exit fullscreen mode

You get it right, but it's not based on svelte store but on Observable. For more api's please check Dexie API Reference.

Now, I have my app where i don't collect their data on our server. Browser have become something so big as an OS, we can do whatever we want to do.

It's a good approach but saving data in browsers have it's on disadvantages so please understand them before adding them to your project.


Till next article have a great life, learn and respect.


This is me writing for you. If you wanna ask or suggest anything please put it in comment and show some love ❤️.