The Easiest Way to Make a Cart in SvelteKit

This blog will show you how to make a cart across pages in SvelteKit the minor drawback is that it is not going to with a database usage just the local storage while easy we tho to use LocalStorage and SvelteKit stores check the official docs for better undersatandign : stores

Just to be clear in the project i used typescript and i downloaded the icons from : Svelte iconify and here is the complete code if you wanna take a look :Github

Disclaimer : Im gonna use types that refer to dummy json api just to make it a bit clear

Create a CartProduct.ts file in the lib directory then add the types

dummy json api

    
        export type Product = {
            id: number;
            title: string;
            description: string;
            category: string;
            price: number;
            discountPercentage: number;
            rating: number;
            stock: number;
            tags: string[];
            brand: string;
            sku: string;
            weight: number;
            dimensions: Dimensions;
            warrantyInformation: string;
            shippingInformation: string;
            availabilityStatus: string;
            reviews: Review[];
            returnPolicy: string;
            minimumOrderQuantity: number;
            meta: Meta;
            thumbnail: string;
            images: string[];
        }
            export type CartProduct = {
            id: string;
            product: Product;
            quantity: number;
        }
    
Character/jumpingCreated with Sketch.

Now the logic

For this we are gonna use : writable: a store you can read and update (like a variable that reacts) readable: a store you can only read, not update directly derived: a store whose value depends on other stores get: instantly read a store’s current value (outside components)

Step One : Checking the browser for existing data

    
        const StoredCart = browser ? localStorage.getItem('cart') : null
        
let initialCart : CartProduct[] = StoredCart ? JSON.parse(StoredCart) : []

This checks if we’re in the browser and loads existing data.

Don’t forget to import false from $app/environment;

Step Two : Create the store

writable makes a reactive value you can read & update — think of it as a magic reactive box


let cartStore = writable<CartProduct[]>(initialCart)
            

Step Three : Keep the browser memory updated

                    
                        if ( browser) {
                            cartStore.subscribe((cart) => {
                                localStorage.setItem('cart', JSON.stringify(cart))
                            })
                        }
                

Every store change is saved to localStorage.

Let's make it useful

A store that calculates things automatically 🤑

derive store for total code

    
        export const cartTotal = derived(cartStore, ($cart) => {
            let ItemCount = $cart.reduce((total, item) => total + item.quantity, 0);
            let subtotal = $cart.reduce((sum, item) => sum + item.product.price * item.quantity, 0);

            return {
                ItemCount,
                subtotal,
                formattedSubtotal: new Intl.NumberFormat('en-US', {
                    style: 'currency',
                    currency: 'USD'
                }).format(subtotal)
            };
        });
    

Important takeaway: think of the reduce method as a way to shrink an array of numbers into its cumulative value.

  • ItemCount — counts how many items are in the cart.
  • subTotal — the total price of the selected items.
  • formattedSubtotal — formats the total, e.g. 100$.

Now the cart the actions ⚙️