State management is a crucial part when working with complex web applications. Svelte does provide us with elegant native stores that can be used in such scenarios. However, we must be cautious while using them otherwise our application may result in unwanted behavior and could produce bugs that are difficult to trace and fix!
One such example is using stores in the backend i.e. in the SSR flow. This article will focus on a few edge cases where we must be extremely cautious in the way we use stores or rather state management in general.
Using stores in the backend (SSR mode) causes data leaks between clients.
Servers are stateless i.e. one common space on the server is shared by multiple clients (users). In other words, the state on Server is global by default that will be shared by all of its clients. The servers are often long-lived and shared by multiple users. For that reason, it's important not to store data in shared variables. For example, consider the following scenario:
Multiple users have been logged into the system and they are interacting with a common application server. Now each user interacts with the server, independently, via the browser. A store is contextual to each instance of your app. This essentially means that the state on the client side is always stateful. If we save any store value on the client side for a particular user, it will remain local to that user and will not be shared with other users.
On the other hand, the state of the server is shared with all the users simultaneously and hence if user "A" updates the store value, that will be reflected on user "B" as well, thus leaking data! In addition, when user "A" returns to the site later in the day, the server may have restarted, losing their data. The main thing to understand is that as soon as you create a store, it becomes global server-side in an SSR context (= your store is a singleton in memory server-side, so it is shared by all HTTP requests hitting your server).
Read rest of the article on my blogging site