Request Scoped Nanostores
Nanostores is a great and super compact state management library that is compatible with multiple frameworks, even with multiple at the same time. Nanostores has been Astro’s recommended option for sharing state between components and between client islands.
Using Nanostores directly with Astro has some caveats, as explained on Astro’s “Why Nano Stores?” FAQ. They are meant for the client-side. Using them on the server, be it on framework components or on the frontmatter of Astro components, may cause problems with data race between requests. Once the page is rendered, the stores on the client won’t have the data from the stores on the server, which may cause flickering and flashing of content on the screen as the client renders a different content from the server.
This integration bridges this gap and enables the use of Nanostores in Astro across server and client isolated on each request.
Installing the dependency
Prerequisites
When using the Cloudflare adapter, you’ll need to enable AsyncLocalStorage manually.
Demo
A demo reading cookies to set the request state on the server and use it interactively on the client is available here:
- Deployed site: https://inox-tools-ex-request-nanostores.pages.dev/
- Source code: https://github.com/Fryuni/inox-tools/tree/main/examples/request-nanostores
This demo project is based on Astro’s with-nanostores
template.
How to use
Wrap your stores using the shared
function, giving it a name.
The store name must be unique across your entire project!.
It doesn’t have to be an atom! You can use any store that is based on an atom:
Example
If you have a comments section on your page, you can create a store that will be shared between the page and all components.
A Preact component to show the comments.
A Solid component to show the number of comments.
And an Astro page that loads the comments for the page and uses both components. The comments will be available for the components to render on the server and on the client for interactivity.
License
Request Nanostores is available under the MIT license.