Natrix.Swr 0.19.0

dotnet add package Natrix.Swr --version 0.19.0
                    
NuGet\Install-Package Natrix.Swr -Version 0.19.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Natrix.Swr" Version="0.19.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Natrix.Swr" Version="0.19.0" />
                    
Directory.Packages.props
<PackageReference Include="Natrix.Swr" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Natrix.Swr --version 0.19.0
                    
#r "nuget: Natrix.Swr, 0.19.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Natrix.Swr@0.19.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Natrix.Swr&version=0.19.0
                    
Install as a Cake Addin
#tool nuget:?package=Natrix.Swr&version=0.19.0
                    
Install as a Cake Tool

Natrix.Swr

Data fetching for Natrix components, ported from React SWR.

The name is the strategy: stale-while-revalidate. A component asks for a key, gets whatever is already cached for it straight away, and a request runs in the background to replace it. Components asking for the same key share one request and one value.

dotnet add package Natrix.Swr

Setup

Register a cache on the host before mounting. There is no ambient default — a process-wide cache would be the wrong thing on a server rendering one visitor's request after another.

using Natrix.Swr;

using var app = new NatrixHostBuilder()
    .UseRootElement(rootElement)
    .UseLifecycleHooks()
    .SetFeature(serializerOptions)
    .UseSwr()
    .UseRootComponent(() => new App { Props = new() })
    .Build()
    .Mount();

Serializer options are required: they are what carries a value from the server's render into the page the browser hydrates from, described under Server rendering. They are taken from the JsonSerializerOptions registered as a feature, so an application that already configures serialization does not hand SWR the same thing twice; pass UseSwr(serializerOptions: …) to override. With neither, Mount() says so.

UseSwr registers middleware rather than a feature, and the cache it builds is published to the component tree at mount. That ordering is the point: the cache is built out of other features — the serializer options, and whichever side of the hydration boundary this host is on — and registration happens while the application is still being described, in an order nothing guarantees. UseSwr can therefore go anywhere in the chain. If you need the cache yourself, build it and pass it in:

var cache = new SwrCache(serializerOptions);
builder.UseSwr(cache: cache);

A fetched type the options cannot describe is reported the same way, at the Use call that introduced it rather than at the render that would have shipped it.

Fetching

Call SwrResource.Use from a component's Setup and render from the signals it returns.

public sealed class UserCard : BaseComponent<UserCardProps, NoEvents, NoSlots, NoExpose>
{
    protected override IComponent[] Setup(out NoExpose exposed)
    {
        exposed = default;

        var user = SwrResource.Use(
            () => ("user", Props.UserId.Value),
            async (key, ct) => await api.GetUserAsync(key.Item2, ct));

        return
        [
            new If
            {
                Condition = user.IsLoading,
                Then = () => [new Spinner { Props = new() }],
                Otherwise = () =>
                [
                    new DomText { Text = new Computed<string>(() => user.Data.Value?.Name ?? "—") },
                ],
            },
        ];
    }
}

Keys

A key is an ordered list of typed segments. Return a tuple and the types flow through to the fetcher, which reads its parameters back as what they were:

var posts = SwrResource.Use(
    () => ("user", userId.Value, "posts"),
    (key, ct) => api.GetPostsAsync(key.Item2, ct));

Signals read inside the factory are tracked, so the resource follows them: when the key changes it rebinds, shows whatever is cached for the new key, and refetches. A factory that re-runs and produces the same key changes nothing.

A tuple has no absent value of its own, so pausing — the equivalent of React SWR's null key — is spelled null. A paused resource never fetches and reports no data, which is how a request that depends on something not ready yet is expressed. Name the type arguments, since a conditional with null in it gives the compiler nothing to infer them from:

var user = SwrResource.Use<(string, string), User>(
    () => session.Value is { } s ? ("user", s.UserId) : null,
    (key, ct) => api.GetUserAsync(key.Item2, ct));

Overloads taking a SwrKey remain for keys whose arity or types are not known at the call. There the fetcher reads segments by position — key.Segment<string>(1) — and pauses with SwrKey.None. A key of plain strings can still be written as a collection expression:

SwrKey key = ["user", userId, "posts"];
How keys become cache entries

A key is filed under a canonical JSON encoding of its segments, so ["ab", "c"] and ["abc"] are different keys and no segment value can collide with another key by containing a separator.

The encoding takes the contracts for your own types from the JsonSerializerOptions below, but none of their formatting: it fixes the naming policy, the encoder, number handling and null handling itself, and sorts object properties. That is deliberate. A serializer guarantees a value survives a round trip — not that two values encode alike exactly when they are equal, which is the opposite property and the one an identity needs. Left to an application's own options, hiding nulls would make two different keys collide, a naming policy that differs between the server and the browser would hide the whole hydration payload, and a dictionary built in a different order would become a second cache entry.

Segment types the library covers — the primitives, Guid, the date and time types, Uri — need no registration. Anything else needs [JsonSerializable] on the shared context, and a typed Use reports a missing one at the call — including for a key that starts out paused, which has no segments to encode yet and would otherwise fail from whatever later unpauses it.

The fetcher is handed the key it is loading. Read the parameters back out of it rather than closing over signals, so the request can never disagree with the key its result is cached under.

That rule is about what identifies the data. Ambient conditions the request happens to run under — an auth token, a base address, whether the service is currently up — are not part of a key: an outage does not change which user you asked for, and keying it would make the same user into two cache entries. The test is whether the thing you are tempted to leave out could ever produce a different value for the same key. If it could, it identifies the data and belongs in the key; if it can only change whether the request succeeds, it does not.

What you get back

Member Meaning
Data Cached value for the current key, default until one arrives. Stays put across revalidations and failures.
Error Last error, set once a request has given up and cleared by the next successful fetch.
IsLoading A request is in flight and there is no value yet — the initial load, retries included. A subset of IsValidating.
IsValidating A request is pending or in flight, retries included — from the moment a key that will be fetched is bound. Also true while refreshing data already on screen.
Key The key currently bound.
RevalidateAsync() Refetches, or joins the request already running.
MutateAsync(value) Writes a value into the cache — every component on that key updates — and refetches to confirm it.
MutateAsync(update) Same, deriving the new value from the current one.

MutateAsync cancels whatever request is in flight first: a response already on its way describes the state before the mutation, and letting it land would undo it.

await todos.MutateAsync(current => [.. current ?? [], newTodo], revalidate: false);

Options

This port covers error retries and where a resource fetches, and nothing else. React SWR's refresh intervals, revalidate-on-focus, deduping windows and fallback data are deliberately absent rather than half-implemented.

Option Default Meaning
ShouldRetryOnError true Whether a failed fetch is retried at all.
ErrorRetryCount 3 Additional attempts after the first failure. React SWR retries forever; a bound is the safer default in a browser tab.
ErrorRetryInterval 5s Base backoff. Attempt n waits ErrorRetryInterval * 2^n, capped at 2^8, without jitter.
FetchOnServer true Whether the fetcher runs during server rendering. false makes the resource client-only — see Client-only resources.

Set the defaults app-wide, and adjust them per resource through a callback that receives them:

builder.UseSwr(new SwrOptions { ErrorRetryCount = 5 });

var user = SwrResource.Use(key, fetcher, options => options with { ShouldRetryOnError = false });

The callback shape is deliberate. Handing Use a whole SwrOptions would replace the application's defaults rather than layer on them, so a resource that only meant to change the retry count would silently take ShouldRetryOnError, ErrorRetryInterval and anything added later from the type's own defaults instead of the app's.

Error is published only once the retries give up, as in TanStack Query rather than React SWR, which reports each attempt's failure as it happens. Until then the key is still being worked on: IsValidating stays true for the whole sequence, and so does IsLoading when no value has arrived yet, since a retry is still the initial load. All three settle together on the final attempt.

Behaviour worth knowing

The fetcher is never called synchronously. Every request — the one a binding issues, an explicit RevalidateAsync, the refetch after MutateAsync — yields to the next cycle of the event loop before it calls the fetcher. IsValidating is true from the moment the request starts; MutateAsync writes its value immediately. Setup runs inside the parent's render, and a fetcher that completed on the spot would otherwise write into the middle of it — and hand the first render of a hydrated page a value the server's markup never had. The deferral makes the first render of any key the page did not carry the loading state, whatever the fetcher's speed.

Requests are deduplicated while in flight. Ten components mounting on the same key issue one request. There is no time-based deduping window: once a request finishes, the next revalidation starts a new one.

The cache outlives components. Unmounting releases a component's claim on an entry but keeps its value, so remounting renders immediately and revalidates in the background. When the last component watching a key goes away, its in-flight request and any queued retry are cancelled — the fetcher's CancellationToken fires.

Entries are never evicted automatically. Call SwrCache.Remove(key) or SwrCache.Clear() for keys that must not accumulate or must not survive a sign-out. Components currently bound to a removed key keep showing what they have until their key changes or they unmount; the next component to ask for it starts fresh.

Signals are not thread-safe, and neither is this. Continuations are resumed on the synchronization context the request started on, which in a browser is the single UI thread.

Server rendering

A server-rendered page arrives with its data already in it, and the browser fetches nothing to display the first screen.

Binding a key during server rendering registers a prefetch with IServerPrefetchFeature. Prefetches start as they are registered and run concurrently, and the SSR host waits for all of them before it writes the response. The values land in that request's cache, the markup is rendered from them, and the cache is serialized into the page's hydration state. On the client the cache is seeded from that payload before the first component binds, so the first render matches the server's markup and no revalidation is issued for data that arrived with the page.

That feature is also how a resource tells which side it is on: where it is present, the fetcher runs only through the prefetches it waits for; where it is absent, the resource takes itself to be in a browser and fetches after its first render. A server host must therefore register it, as the project template does, and Mount() refuses a host that has server hydration state without it — the requests would otherwise start during the render and outlive the response.

Both hosts need the same serializer context, which is why the fetched types belong in a project the client and the server both reference:

[JsonSerializable(typeof(UserProfile))]
public sealed partial class AppJsonContext : JsonSerializerContext;

Source-generated metadata is what keeps the transfer working under the client's trimming and AOT compilation. A type the context does not cover is reported at the Use call that introduced it, not at render time.

Put that context in the resolver chain of each host's options and register those options as a feature. On a server that already serves JSON, the options its own endpoints use are the ones to register, so nothing in the render can disagree with what the browser will read:

// Server
builder.Services.ConfigureHttpJsonOptions(options =>
    options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default));

var serializerOptions = httpContext.RequestServices
    .GetRequiredService<IOptions<JsonOptions>>().Value.SerializerOptions;

// Client — web defaults, because that is what the server's options start from. The chain settles
// which types can be resolved and carries whatever converters the generator baked in; naming
// policy and case sensitivity belong to the options themselves, so both sides have to agree on
// them separately or every property silently reads as null.
var serializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
    TypeInfoResolverChain = { AppJsonContext.Default },
};

The fetcher runs on both sides, so it has to be able to reach the API from both. In the browser that usually means a relative URL against the page's origin; on the server, an absolute one built from the request being answered.

Rules the transfer follows:

  • A key that fails on the server fails the render. The exception leaves the prefetch drain, and the host answers with an error instead of a page missing data it asked for. Let it propagate: a host that caught it and served the page anyway would render the error state into markup the client — which receives no error — cannot reproduce. Data the page can do without belongs in a client-only resource, which the server never fetches.
  • The server fetches only through the prefetch feature. A request started anywhere else would outlive the response. Which is also why a client-only resource, which registers no prefetch, never runs its fetcher on the server at all. The request's cancellation reaches every prefetch's fetcher, so an aborted request does not keep fetching for a page nobody is waiting for.
  • Server prefetches do not retry. A failing upstream would otherwise hold the response open for the whole backoff sequence; the first failure fails the render instead.
  • Two components on one key cost one prefetch. Prefetches run concurrently, so the second usually finds the first one's request in flight and joins it; one that arrives after the value has landed finds the value. Only a server prefetch's request is joined: a run started from Setup by an explicit revalidation or a mutation carries retries and swallows its failure, so a prefetch cancels it and issues its own.
  • Hydration covers the pass that reproduces the markup, and nothing after it. A key bound while the page hydrates renders the value it shipped with and is not revalidated. Every bind once that synchronous pass has returned revalidates — a component mounted later on a key another one still holds included — and payload for keys nothing bound during the pass is dropped. An explicit RevalidateAsync() always fetches.

Client-only resources

Not everything should be fetched on the server: a request that needs a browser-only API or a credential only the browser holds, a value personal to the visitor that must not end up in cacheable markup, or an upstream too slow to hold the response for. Turn FetchOnServer off for those, and leave it on for the rest — the setting is per resource, so one page can mix both:

var profile = SwrResource.Use(
    () => ("profile", userId.Value),
    (key, ct) => api.GetProfileAsync(key.Item2, ct));

var notifications = SwrResource.Use(
    () => ("notifications", userId.Value),
    (key, ct) => api.GetNotificationsAsync(key.Item2, ct),
    options => options with { FetchOnServer = false });

The fetcher of a client-only resource never runs on the server. The server renders its loading state, and the hydration payload carries nothing for its key, so the client's first render shows the same loading state as the markup and the request goes out on the cycle after it — exactly what happens for any key the page did not carry. FetchOnServer has no effect in the browser.

The setting belongs to the caller, not to the cache entry. A client-only resource that shares a key with one that does fetch on the server receives the prefetched value like any other subscriber, and is hydrated from it on the client.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.19.0 109 10/10/2026
0.18.0 107 10/10/2026
0.17.0 111 10/10/2026
0.16.0 108 10/6/2026
0.15.0 106 10/1/2026
0.14.1 102 9/30/2026
0.14.0 108 9/30/2026