Composite Keys
When a fetcher depends on extra context beyond the URL — an auth token, tenant ID, or locale — a plain string key like "/api/user" means the cache won’t vary when that context changes. You’d get the wrong cached data.
Composite keys solve this: the tuple is both the cache key and the fetcher arguments, always in sync.
Two-Part Key
Section titled “Two-Part Key”Pass a tuple of (url, arg). Different argument values produce separate cache entries, and the fetcher receives both parts as separate parameters:
var result = swr.Use<User, string>( ("/api/user", authToken), (url, token) => http.GetFromJsonAsync<User>($"{url}?token={token}"));When authToken changes, SWR treats it as a new cache entry and fetches fresh data.
Three-Part Key
Section titled “Three-Part Key”For scenarios with multiple context values, use a three-part tuple:
var result = swr.Use<Product[], string, string>( ("/api/products", tenantId, locale), (url, tenant, loc) => FetchProducts(url, tenant, loc));Each unique combination of (url, tenantId, locale) gets its own cache entry.
How It Works
Section titled “How It Works”Under the hood, tuple keys are composed into a single cache key string using the :: separator via SwrCacheKey.From:
/api/user::token-abc/api/products::tenant-1::en-USThe fetcher is wrapped so it always receives the original tuple parts as separate arguments — you never have to parse the composite key yourself.
Null Arguments
Section titled “Null Arguments”Null argument values are safe — they’re serialized as empty strings in the cache key:
// Cache key: "/api/data::"var result = swr.Use<Data, string?>( ("/api/data", null), (url, arg) => FetchData(url));When to Use Composite Keys
Section titled “When to Use Composite Keys”Use composite keys when the same URL should return different data depending on context:
- Authentication: Token or session changes should fetch fresh data
- Multi-tenancy: Different tenants see different data at the same endpoint
- Localization: Locale changes require re-fetching localized content
- Feature flags: Different flag states produce different responses