How to share a store between 2 SSR svelte apps
By default, when you have 2 Svelte apps that are server-side rendered, they won’t share a store. So let’s take a look into how to solve this.
Basket example:
Basket.Svelte
javascript
<script lang="ts">
import {store} from './store'
</script>
{#if $store.showBasket}
<div id="overlay" on:click={() => ($store.showBasket = !$store.showBasket)} />
<div id="shopping-basket" />
{/if}
BasketButton.Svelte
javascript
<script lang="ts">
import {store} from './store'
</script>
<button on:click={() => ($store.showBasket = !$store.showBasket)}> The button </button>
We want both of the apps to have control over when to display the basket.
- When clicking the overlay of the basket
- When clicking the button
Here’s how to make it work:
store.ts
typescript
import {writable} from 'svelte/store'
function createStore() {
return writable({showBasket: false})
}
function getStore() {
if (typeof window === 'undefined') return createStore()
window.store = window.store || createStore()
return window.store
}
export const store = getStore()
We get the store from the window, and if it doesn’t exist we create a new store and attach it to the window.