This repo demonstrates how to use TanStack Query (Svelte Query) with Astro - something that isn't as straightforward as you might expect due to how Astro's island architecture works.
When trying to use Svelte Query with Astro, you'll likely run into this error:
Error: No QueryClient was found in Svelte context. Did you forget to wrap your component with QueryClientProvider?
This happens because Astro's islands are isolated JavaScript contexts, and Svelte's context API doesn't work across them.
We solved this by creating wrapper components that keep the QueryProvider and query components together in the same island:
Astro Page
└── Wrapper Component (client:only="svelte")
├── QueryProvider
└── Data Component (uses createQuery)
Here's a diagram showing how components are structured in this pattern:
- QueryProvider.svelte - Sets up the QueryClient
- QueryRoot.svelte - Combines the provider with the Posts component
- PostRoot.svelte - Combines the provider with the individual Post component
- Each Astro page imports its own wrapper component
- The wrapper includes both the provider and data component
- We use
client:only="svelte"on the wrapper, not individual components - This keeps the context chain intact within each island
To use this pattern in your own project:
- Create a base QueryProvider component
- Create wrapper components for each major data need
- Use these wrappers in your Astro pages with
client:only="svelte" - Handle dynamic routes with either:
getStaticPaths()for known routesexport const prerender = falsefor SSR (requires setup)
Astro's partial hydration creates isolated "islands" of interactivity. Svelte's context API can only share context within a component tree, not across islands.
By wrapping related components together, we keep everything that needs to share context in the same island.
- Organize by domain - Create wrappers for different sections of your app
- Consistent query keys - Use prefixes like
['posts'],['post', id] - Optimize performance - Set appropriate
staleTimeandcacheTimevalues - Consider persistence - Add storage persistence for better UX
