Skip to content

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.

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.

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.

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-US

The fetcher is wrapped so it always receives the original tuple parts as separate arguments — you never have to parse the composite key yourself.

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));

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