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
The Easiest Way to Make a Cart in SvelteKit
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
Now the logic
First : SvelteKit Stores
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 🤑
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$.