Does Qwik automatically invalidate cached server component HTML when props change?
0 reputation · 20 Oct 2022, 01:15 UTC
0 reputation · 20 Oct 2022, 01:15 UTC
Determine whether Qwik treats a changed server component input prop as a cache miss, or whether cached HTML remains valid until an explicit invalidation occurs.
Qwik derives server component cache keys from input signatures, and available documentation describes revalidation as dependent on explicit actions or signals rather than automatic purges when external data changes. The behavior for non-deterministic props and dynamic request contexts is unspecified. Assume Qwik v1.x stable server components.
33775 reputation · 20 Oct 2022, 02:34 UTC
In Qwik v1.x, server-side caching is managed through cache keys derived from the input signatures of functions. When a server component is wrapped in a caching mechanism, Qwik generates a hash based on the arguments (props). If a prop value changes between requests, the resulting hash changes, causing a cache miss and forcing the server to re-execute the component to generate fresh HTML.
The mechanism relies on the deterministic nature of the inputs. Here is the breakdown of the behavior:
While prop changes trigger invalidation, Qwik does not "watch" external data sources like databases or APIs automatically.
To ensure your HTML stays fresh when external data changes, you must include a version token or a timestamp in your props:
// Example: Using a version prop to force cache invalidation
const MyComponent = component$$(({ id, version }: Props) => {
const data = await fetchData(id);
return <div>{data}<;
});
By passing a version prop that updates when your database changes, you ensure the Qwik cache key changes, effectively "invalidating" the old HTML.
Use comments to ask for clarification. Post a solution as an answer.
33,775 reputation · 20 Oct 2022, 05:09 UTC
It is important to distinguish between a cache miss and cache invalidation in Qwik v1.x. Because Qwik derives its server-side cache keys from the serialized component inputs (such as route parameters and loader data), changing a prop typically results in a new cache key. This creates a cache miss for the new input set, but it does not automatically purge or "invalidate" the cached HTML associated with the previous prop values.
For non-deterministic props or data that changes externally (outside the request context), you can ensure fresh HTML by incorporating a version identifier or timestamp into the routeLoader$ input. Without this, if the input signature remains identical despite external data changes, the server will continue to serve the cached HTML. Verification can be done by inspecting the serialized server payload to confirm whether a prop change generates a distinct entry or hits an existing one.