Skip to content

Advanced

Controls request deduplication behavior. There are two deduplication strategies:

  • By loading state — prevents new requests if one is already in progress
  • By time window — prevents requests within the dedupe time window (queries only, not mutations)

Default: both enabled.

import { client, dedupe } from '@nano_kit/query'
/* Disable time-based deduplication, keep loading state deduplication */
const { query } = client(
dedupe(true, false)
)
/* Disable all deduplication for a specific query */
const [$post] = query(PostKey, [$postId], fetchPost, [
dedupe(false)
])

For mutations, only loading state deduplication is available:

const [updatePost] = mutation(updatePostFn, [
dedupe(false) /* Allow concurrent mutation calls */
])

When to use: Allow multiple simultaneous requests for the same data, such as polling or real-time updates.

Disables request execution based on a signal value. When the signal returns true, requests are not made.

import { signal, computed } from '@nano_kit/store'
import { client, disabled } from '@nano_kit/query'
const $isAuthenticated = signal(false)
const $userId = signal(null)
const { query } = client()
/* Disable query when user is not authenticated */
const [$user] = query(UserKey, [$userId], fetchUser, [
disabled(computed(() => !$isAuthenticated()))
])

When to use: Conditionally enable queries based on application state, such as authentication status. When a query waits for a parameter to have a value, wrap the parameter in required() instead: the fetcher then receives it without undefined, and no cache entry is created in the meantime.

Customizes how errors are converted to strings for storage in cache signals. By default, errors are mapped to error.message.

import { client, mapError } from '@nano_kit/query'
/* Global error mapping */
const { query } = client(
mapError((err) => {
if (err instanceof NetworkError) {
return `Network error: ${err.code}`
}
return `Error: ${err.message}`
})
)
/* Per-query error mapping */
const [$post] = query(PostKey, [$postId], fetchPost, [
mapError((err) => {
if (err.status === 404) {
return 'Post not found'
}
return 'Failed to load post'
})
])

When to use: Custom error formatting, localization, or extracting specific information from custom error types.

Sets a Codec for query cache entry data when the cache crosses a serialization boundary.

You do not need this for ordinary in-memory browser cache usage. While the app is running in the browser, cache entries can hold any JavaScript value directly. A codec is only needed when query cache data must be serialized: for SSR dehydration/hydration or for persistent storage.

Use it when serialized cache entries contain values that need custom encoding, such as Date, Map, Set, class instances, or encrypted/compact payloads.

hydratable() and persistence() use the codec when they dehydrate data, hydrate it back, write it to persistent storage, or read it back.

import type { Codec } from '@nano_kit/store'
import { parse, stringify } from 'devalue'
import { client, codec, hydratable } from '@nano_kit/query'
const DevalueCodec: Codec<unknown, string> = {
encode: stringify,
decode: value => value === null ? null : parse(value)
}
export function Client$() {
return client(
codec(DevalueCodec),
hydratable()
)
}

With a codec like this, data containing values such as Date, Map, or Set can be dehydrated on the server and restored on the client without losing those types.

The codec applies to cached data. Query metadata such as revision, dedupe time, and expiration time is handled by the query package itself.

When to use: SSR hydration or persistent storage for cache entries that contain non-plain values or require a custom serialized format.

Registers a global error handler called for every query or mutation error. The callback receives the error and a stopped boolean indicating if error propagation was stopped.

import { client, onEveryError } from '@nano_kit/query'
const { query } = client(
onEveryError((error, stopped) => {
if (!stopped) {
/* Log to error tracking service */
errorTracker.log(error)
/* Show user notification */
showErrorToast(String(error))
}
})
)

You can prevent the global handler from running using stopErrorPropagation in request context:

import { onError, stopErrorPropagation } from '@nano_kit/query'
const [$post] = query(PostKey, [$postId], (id, ctx) => {
/* Stop error conditionally */
onError(ctx, (error) => {
if (error.message.includes('404')) {
/* Handle 404 silently */
stopErrorPropagation(ctx)
}
})
/* Or stop all errors */
stopErrorPropagation(ctx)
return fetchPost(id)
})

When to use: Centralized error handling, logging, or user notifications. Combine with stopErrorPropagation to handle specific errors locally without triggering global handlers.

Every queryKey() builder is registered automatically. Use eachKeyBuilder() to iterate over cache key builders:

import { client, eachKeyBuilder, queryKey } from '@nano_kit/query'
const PostKey = queryKey<[id: number], Post>('post')
const UserKey = queryKey<[id: number], User>('user')
const { revalidate, invalidate } = client()
/* Mark every registered query shard as stale */
eachKeyBuilder(revalidate)
/* Or remove every registered query shard from cache */
eachKeyBuilder(invalidate)

This is useful after broad application changes, such as sign in, sign out, locale changes, or any mutation that can affect several query domains at once.

The name of a builder is its cache shard: two builders with one name share one cache.

A builder passed to revalidate(), invalidate() or $data() reaches every entry of its shard. To reach only some of them, add the keys() extension: its eachKey() calls back with every cached key of a builder, and each key carries the parameters it was loaded with:

import { client, keys, queryKey } from '@nano_kit/query'
const PostsKey = queryKey<[authorId: number, search: string], Post[]>('posts')
const { eachKey, revalidate } = client(keys())
/* Refetch only the searches among the posts of author 1 */
eachKey(PostsKey, (key) => {
const [authorId, search] = key.params
if (authorId === 1 && search) {
revalidate(key)
}
})

The key works with every method that takes a concrete key: revalidate(), invalidate(), $data() and $error(). Iteration is batched, as with eachKeyBuilder().

An entry that was only read, or written before its first load, has no parameters yet: its key comes with an empty params array.

For comfortable cache mutations, use helpers that fit naturally into $data reducers. They are especially handy for optimistic updates.

Use append, prepend, drop, restore, map, and sort for array cache values:

import {
append,
client,
drop,
map,
prepend,
queryKey,
restore,
sort
} from '@nano_kit/query'
const PostsKey = queryKey<[], Post[]>('posts')
const { $data } = client()
/* Add to the end. If cache is empty, creates a one-item array. */
$data(PostsKey(), posts => append(posts, newPost))
/* Add to the beginning. */
$data(PostsKey(), posts => prepend(posts, pinnedPost))
/* Remove matching items. */
$data(PostsKey(), posts => drop(posts, post => post.id === removedPostId))
/* Remove optimistically: if the request fails, revert() puts the items back. */
const isRemoved = (post: Post) => post.id === removedPostId
const revert = $data(
PostsKey(),
posts => drop(posts, isRemoved),
(current, prev) => restore(current, prev, isRemoved)
)
/* Transform items. */
$data(PostsKey(), posts => map(posts, post => ({
...post,
stale: true
})))
/* Sort without mutating the previous array. */
$data(PostsKey(), posts => sort(posts, (a, b) => b.createdAt - a.createdAt))

The helpers return the original empty value for operations where that makes sense, or create a new array when adding a value.

restore undoes a drop as the third argument of $data. It puts removed values back at their previous indexes in the array as it is by now, so what was written since stays. An array that holds a matching value again, as after a refetch, stays as it is. A previous index can be off by what was added since, so when the client knows the order of the list, such as by date, wrap the result in sort.

Use mapPages, mapPageAt, mapFirstPage, mapLastPage, sortPages, and restorePages for InfinitePages data:

import {
type InfinitePages,
client,
drop,
mapFirstPage,
mapPages,
prepend,
queryKey,
restorePages,
sortPages
} from '@nano_kit/query'
interface PostsPage {
posts: Post[]
nextCursor?: number
}
const FeedKey = queryKey<[], InfinitePages<PostsPage, number>>('feed')
const { $data } = client()
/* Update every page. */
$data(FeedKey(), data => mapPages(data, page => ({
...page,
posts: page.posts.map(post => (
post.id === updatedPost.id ? updatedPost : post
))
})))
/* Add an item to the first loaded page. */
$data(FeedKey(), data => mapFirstPage(data, page => ({
...page,
posts: prepend(page.posts, newPost)
})))
/* Sort items across all pages while preserving page sizes. */
$data(FeedKey(), data => sortPages(
data,
(a: Post, b: Post) => b.createdAt - a.createdAt,
(sort, page) => ({
...page,
posts: sort(page.posts)
})
))
/* Remove optimistically: if the request fails, revert() puts the items back. */
const isRemoved = (post: Post) => post.id === removedPostId
const revert = $data(
FeedKey(),
data => mapPages(data, page => ({
...page,
posts: drop(page.posts, isRemoved)
})),
(current, prev) => restorePages(current, prev, isRemoved, (restore, page) => ({
...page,
posts: restore(page.posts)
}))
)

sortPages collects items from every page, sorts the combined list, and writes items back into the original page chunks. Pagination metadata such as next and more stays intact.

restorePages puts removed items back into the pages they stood in, and its callback adapts the page shape the same way. Pages stay as they are when a matching item is back on any page, as a refetch can do, and a page that is no longer loaded gets nothing back. As with restore, when the client knows the order of the list, wrap the result in sortPages.

Query and mutation fetcher functions receive request context as last parameter. It provides methods to manage request lifecycle:

  • onSuccess(ctx, fn) - register success callback
  • onError(ctx, fn) - register error callback
  • onSettled(ctx, fn) - register settled callback
  • stopErrorPropagation(ctx) - stop error propagation to global onEveryError handler
  • previous(ctx) - get the promise of the previous request to wait for it
import { client, mutations, onSuccess, onError, onSettled, stopErrorPropagation } from '@nano_kit/query'
const { mutation } = client(mutations())
/* ... */
const [updatePost] = mutation<[params: UpdatePostParams], Post>(
(params, ctx) => {
onSuccess(ctx, (data) => {
/* Data updated successfully */
})
onError(ctx, (error) => {
/* Handle error */
})
onSettled(ctx, (data, error) => {
/* Always executed */
})
/* Mark error as stopped to prevent global error handling */
/* Can be invoked in onError callback as well */
stopErrorPropagation(ctx)
return PostsService.update(postId, params)
}
)

Also query’s context can be used as a cache key for advanced scenarios:

import { client, queryKey } from '@nano_kit/query'
const TagsKey = queryKey<[postId: number], Tag[] | null>('tags')
const $postId = signal(1)
const {
query,
$data
} = client()
const [$tags, $tagsError] = query(TagsKey, [$postId], async (postId, ctx) => {
/* Use ctx as current query key to accumulate data in the cache */
const prevTags = $data(ctx) || []
const newTags = await PostsService.fetchTags(postId)
return [...new Set(prevTags.concat(newTags))]
})

previous(ctx) returns the promise of the previous request of the same query, operation or mutation, or undefined if there is none. Await it to run requests one after another, for example to send autosaves in the order they were made:

import { client, mutations, dedupe, previous } from '@nano_kit/query'
const { mutation } = client(mutations())
/* ... */
const [savePost] = mutation<[params: UpdatePostParams], Post>(
async (params, ctx) => {
/* Start once the previous save has settled */
await previous(ctx)
return PostsService.update(params)
},
[
/* Queue calls made during a save instead of dropping them */
dedupe(false)
]
)

The promise never rejects: it resolves with the [data, error] result of the previous request, or with undefined if that request was aborted, so a failed request does not stop the next ones.

Mutations and operations drop a call made while a request is in flight, so disable deduplication by loading state with dedupe(false) to queue such calls. Queries and infinite queries need no extra settings: a request for new parameters is never dropped, and $loading stays true while it waits.

With abortable, take abortSignal(ctx) before awaiting previous(ctx) to be able to abort a request that is still waiting.

Operations are a special type of reactive primitive that combines features of queries and mutations. They are essentially “manual queries” — they don’t fetch automatically on mount or parameter changes, but they maintain state in the cache like queries.

Use operation() from the client with the operations() extension. Like queries, you need to define an operationKey:

import { client, operations, operationKey } from '@nano_kit/query'
/* Define operation key */
const GenerateKey = operationKey<[], [prompt: string], GeneratedPost>('generate')
const { operation } = client(
operations()
)
/* Create operation */
const [generate, $result, $error, $loading] = operation(GenerateKey, [], (prompt) => PostsService.generateWithAi(prompt))

Operations are executed manually like mutations, but their result is stored in the cache identified by the key constructed from arguments:

/* Execute operation manually */
const [result, error] = await generate('Write a post about React')
FeatureQueryMutationOperation
ExecutionAutomatic (reactive)ManualManual
CachingYes (all calls)No (result only)Yes (all calls)
DeduplicationYesLoading onlyYes
Use CaseFetching data for UIModifying data on server”Heavy” computations, on-demand fetching with cache

Use operations for:

  • Expensive calculations that should be cached but triggered manually (e.g., AI generation, reports).
  • Lazy loading data that shouldn’t be loaded immediately on mount.
  • Search actions where you want to cache results for specific search terms but trigger the search manually (e.g., on button click submit).

Infinite queries enable pagination and “Load More” patterns by maintaining an array of pages in the cache.

Use infinite() from infinites() extension. It requires a getNextCursor function to determine the next page’s cursor. The function returns a falsy value, like undefined, null or false, when there is no next page.

import { type InfinitePages, client, infinites, queryKey } from '@nano_kit/query'
interface PostsPage {
posts: Post[]
nextCursor?: number
}
/* 1. Define key with InfinitePages<Data, Cursor> type */
const PostsKey = queryKey<[], InfinitePages<PostsPage, number>>('posts')
const { infinite } = client(infinites())
/* 2. Create infinite query */
const [fetchNext, $data, $error, $loading, $nextError, $nextLoading] = infinite(
PostsKey,
[],
(lastPage) => lastPage.nextCursor, /* Extract next cursor from page */
(cursor) => fetchPosts({ cursor }) /* Fetcher receives cursor */
)

Returns a tuple with:

  • fetchNext: Function to load the next page.
  • $data: Signal with InfinitePages object:
    • pages: Array of all loaded pages P[].
    • next: The next cursor value C, or undefined after the last page.
    • more: Boolean indicating if next cursor is present.
  • $error: Signal with error message (or null).
  • $loading: Signal indicating loading state.
  • $nextError: Signal with error message of the next page (or null).
  • $nextLoading: Signal indicating that the next page is loading.
  • $key: Signal with current cache key.

Revalidating an infinite query, with revalidate() or by reading it again once the dedupe window has closed, refetches every loaded page: the first one, then each next one by the cursor of the page before it. The new pages replace the loaded ones at once, so a long list keeps its length and stays on screen while it loads. If a page fails, the loaded pages stay with the error. New parameters start over from the first page, and so does invalidate(), which drops the pages.

$error and $loading cover every request of the list: the first page, the next one and a refetch of the loaded pages. $nextError and $nextLoading cover the next page alone, so a refetch does not show Load More as loading, and a failed refetch is not taken for a failed next page: retry the next page with fetchNext() and the refetch with revalidate().

Here is a small usage example in a React component:

import { useSignal } from '@nano_kit/react'
export function PostsList() {
const data = useSignal($data)
const loading = useSignal($loading)
const nextError = useSignal($nextError)
const nextLoading = useSignal($nextLoading)
if (!data) {
return null
}
/* Access all items from all pages */
const allPosts = data.pages.flatMap(page => page.posts)
return (
<div>
{allPosts.map(post => (
<PostCard key={post.id} post={post} />
))}
{nextError && <p>Could not load more posts: {nextError}</p>}
{data.more && (
<button onClick={fetchNext} disabled={loading}>
{nextLoading ? 'Loading...' : 'Load More'}
</button>
)}
</div>
)
}

Extensions allow you to add extra functionality to the client or individual queries.

Enables automatic retries when a request fails. It uses an exponential backoff strategy by default to determine the delay between attempts.

A retry revalidates the key, so the data on screen stays while it runs, and an infinite query refetches its loaded pages, whose next page then comes with fetchNext as before. The error stays shown between attempts.

import { client, retryOnError } from '@nano_kit/query'
/* Enable retries globally */
const { query } = client(
retryOnError()
)
/* Enable retries for a specific query */
const [$post] = query(PostKey, [$postId], fetchPost, [
retryOnError()
])

By default it uses a jittered exponential backoff. You can provide a custom delay calculator:

retryOnError((count, error) => {
/* Linear backoff: 1s, 2s, 3s... */
return count * 1000
})

When to use: Improve resilience for unstable network connections or transient server errors.

Adds support for request cancellation using AbortController. It injects an AbortSignal into the request context, which you can pass to fetch or other async APIs.

import { client, abortable, abortSignal, abortPrevious, abort } from '@nano_kit/query'
const { query } = client(
abortable()
)
const [$post] = query(PostKey, [$postId], async (id, ctx) => {
/* Abort previous running request for this query */
abortPrevious(ctx)
/* Pass signal to fetch */
return fetch(`/api/posts/${id}`, {
signal: abortSignal(ctx)
}).then(r => r.json())
})

You can also manually abort a running request:

const promise = fetchPost()
abort(promise)

When to use: Data fetching where cancellation prevents race conditions and saves bandwidth when the user navigates away or parameters change quickly (e.g., search-as-you-type).

Revalidates queries when one or more reactive conditions become truthy. Pass any accessor that represents the moment when cached data should be refreshed: page visibility, network state, polling ticks, or your own domain-specific condition.

import { interval } from '@nano_kit/store'
import {
$networkOnline,
$pageVisible
} from '@nano_kit/platform-web'
import { client, revalidateOn } from '@nano_kit/query'
const { query } = client(
revalidateOn(
/* Revalidate when page becomes visible again... */
$pageVisible,
/* ...or when network comes back online... */
$networkOnline,
/* ...or every minute */
interval(60 * 1000)
)
)

Use built-in browser signals from @nano_kit/platform-web for common app lifecycle events:

  • $pageVisible revalidates when the user returns to the page.
  • $networkOnline revalidates when the browser comes back online.
  • interval(ms) from @nano_kit/store revalidates on a timer.

You can also pass your own signal or computed condition:

import { computed, signal } from '@nano_kit/store'
import { client, revalidateOn } from '@nano_kit/query'
const $userId = signal<string | null>(null)
const $ready = computed(() => $userId() !== null)
const { query } = client(
revalidateOn($ready)
)

When to use: Keep data fresh when the page becomes visible again, recover after network outages, poll server state, or revalidate from any domain-specific condition.

Persists the query cache using any storage adapter that implements the Storage interface. The second argument is the data lifetime in milliseconds.

If the client has a codec setting, persisted entry data is encoded before writing and decoded after reading.

import { client, persistence, indexedDbStorage } from '@nano_kit/query'
const { query } = client(
/* Keep cache for 24 hours */
persistence(indexedDbStorage(), 24 * 60 * 60 * 1000)
)

Creates an IndexedDB storage adapter for persistence(), allowing cached data to survive page reloads and act as a cache for offline mode.

It stores entries prepared by persistence(), including data encoded by the current codec setting.

import { client, persistence, indexedDbStorage } from '@nano_kit/query'
const { query } = client(
/* Keep cache for 24 hours */
persistence(indexedDbStorage(), 24 * 60 * 60 * 1000)
)

When to use: Offline-first applications, or faster startup by showing cached data immediately while fetching fresh data.

The entities extension allows you to map query or mutation results to entity references for better cache management and data consistency. Thus you can update entity data in one place and have it reflected across all queries that reference that entity.

import { client, mutations, entity, entities, onError } from '@nano_kit/query'
const PostEntity = entity<Post>('post')
const { query, mutation, $data } = client(
mutations()
)
/* 1. Map individual entity in query */
const [$post] = query(PostKey, [$postId], (postId) => (
PostsService.fetch(postId)
), [
/* Map entity to entity reference */
/* Also every refetch will update entity in the cache */
entities(PostEntity)
])
/* 2. Map list of entities in query */
const [$posts] = query(PostsKey, [], () => (
PostsService.fetchPosts()
), [
/* Map entities in the page to entity references */
/* Also every refetch will update entities in the cache */
entities((capture, page) => ({
...page,
posts: page.posts.map(capture(PostEntity))
}))
])
/* 3. Optimistic update via mutation */
const [updatePost] = mutation<[params: UpdatePostParams], Post>(
(params, ctx) => {
const postId = $postId()
/* Optimistically update entity data, will update all references */
const revert = $data(PostEntity(postId), post => post && ({
...post,
...params
}))
/* Revert changes on error */
onError(ctx, revert)
return PostsService.update(postId, params)
}
)

With this setup:

  1. $post (individual post) and $posts (list of posts) share the same data source for the post entities.
  2. Fetching specific post via $post updates the entity in $posts as well.
  3. updatePost optimistically updates the entity, instantly reflecting changes in both $post and $posts.

The capture helper stores each entity in the shared entity cache and returns a reference for the query result. Passing entities(PostEntity) is the shorthand for a single entity result.

Update an entity by its own key, as updatePost does. A query that maps its result to the entity shows the entity, so a write to the key of that query is not shown.

A query of a single entity can show it before its own result comes. Give entities a second argument that gets the entity id from the query parameters:

const [$post] = query(PostKey, [$postId], (postId) => (
PostsService.fetch(postId)
), [
/* Until its own result comes, shows the post that $posts has loaded */
entities(PostEntity, ([postId]) => postId)
])

A post from the list then shows at once, while its own request confirms it. A created post needs only its entity, $data(PostEntity(post), post), and a mutation with entities(PostEntity) writes even that:

const [createPost] = mutation<[params: CreatePostParams], Post>(
params => PostsService.create(params),
[
/* The page of the new post shows it at once */
entities(PostEntity)
]
)

If the request of the query fails, the entity stays with the error, as cached data does after a failed refetch. While a required parameter has no value, the id function gets the parameters as undefined.

The entity outlives the keys of the queries that show it, so invalidate it too when the post is deleted: invalidate(PostEntity(postId)). Otherwise a page that opens on the post keeps showing it, even after its request fails.

When to use: Complex applications where the same data (e.g., a “User” or “Product”) appears in multiple places or lists and needs to stay synchronized.