Skip to content

Getting Started

SWR .NET brings the stale-while-revalidate caching strategy to .NET. Serve cached data instantly while revalidating in the background — the user always sees data fast, and it’s always eventually fresh.

  • .NET 8.0 or later
  • A Blazor Server, Blazor WebAssembly, or ASP.NET Core project
Terminal
dotnet add package Swr.Net --prerelease
Program.cs
builder.Services.AddSwrForBlazor();
Components/Pages/Home.razor
@using System.Net.Http.Json
@using Swr.Net
@inject ISwr Swr
@inject HttpClient Http
@if (result is { Error: not null })
{
<p class="error">@result.Error</p>
}
else if (result is null or { IsLoading: true, Data: null })
{
<p>Loading...</p>
}
else if (result.Data is not null)
{
<h2>@result.Data.Name</h2>
}
@code {
private SwrResult<User>? result;
protected override void OnInitialized()
{
result = Swr.Use("/api/users/me", FetchUser,
onChange: () => InvokeAsync(StateHasChanged));
}
private Task<User?> FetchUser(string key) => Http.GetFromJsonAsync<User>(key);
}
  • Use<T> returns a SwrResult<T> immediately — cached data renders instantly, fresh data swaps in via the callback
  • You provide the fetcher function — SWR only manages the cache, not how data is retrieved

The second argument to Use<T> is a fetcher — a Func<string, Task<T?>> that receives the cache key and returns the data. SWR never fetches data itself; you decide how to retrieve it:

// HTTP with System.Net.Http.Json
Func<string, Task<User?>> fetcher = key => Http.GetFromJsonAsync<User>(key);
result = Swr.Use("/api/users/me", fetcher, onChange: () => InvokeAsync(StateHasChanged));
// Database query
Func<string, Task<Product?>> fetcher = key => db.Products.FindAsync(int.Parse(key));
result = Swr.Use("product/42", fetcher);
// Any async source
Func<string, Task<Config?>> fetcher = async key =>
{
var json = await File.ReadAllTextAsync($"config/{key}.json");
return JsonSerializer.Deserialize<Config>(json);
};
result = Swr.Use("app-settings", fetcher);

The fetcher can also be a method — useful when the logic is reusable or more complex:

@code {
private SwrResult<User>? result;
protected override void OnInitialized()
{
result = Swr.Use("/api/users/me", FetchUser,
onChange: () => InvokeAsync(StateHasChanged));
}
private Task<User?> FetchUser(string key) => Http.GetFromJsonAsync<User>(key);
}

Because the fetcher is user-provided, you can add auth headers, use gRPC, read from a file, or call any data source — SWR only manages the cache.

  1. Stale — Return cached data instantly. The UI is never blocked.
  2. Revalidate — Fetch fresh data in the background.
  3. Update — Swap in new data. Every subscriber re-renders automatically.
Program.cs
builder.Services.AddSwrForBlazor(options =>
{
options.StaleTime = TimeSpan.FromSeconds(30);
options.CacheTime = TimeSpan.FromMinutes(5);
});