# Plugins

> Give a client its behaviors as plugins, set their per-query options in factories, give every queryFn a typed context, and bind the builders to the client that has them.

A client's behavior beyond caching comes from its **plugins**: retries, polling, refetching on focus, and whatever your app adds. A plugin declares the per-query **options** it reads and the **context** it gives every `queryFn`. A query takes those options, and its `queryFn` gets that context, on the clients that have the plugin.

The per-query behavior that `recommended()` turns on is set this way, in the query's factory:

```ts
import { queryOptions } from "~/raf.ts";

export function postsQuery(input: { page: number; sort: "newest" | "oldest" }) {
	return queryOptions({
		queryKey: posts("list", input),
		queryFn: () => listPosts(input),
		// Options of `retry()` and `focusRefetch()`, which `recommended()` includes.
		retry: 1,
		refetchOnWindowFocus: false,
	});
}
```

This `queryOptions` comes from the app's `raf.ts`, which [binds it to the client](#typing-options-by-the-client), so it takes the options of that client's plugins.

| Option                 | Declared by          | Use                                                                           |
| ---------------------- | -------------------- | ----------------------------------------------------------------------------- |
| `retry`                | `retry()`            | Attempts for this query, or `false`. See [Retries](https://raf-query.katt.dev/docs/retries.md)              |
| `refetchInterval`      | `polling()`          | Refetch every `n` ms while read. See [Polling](https://raf-query.katt.dev/docs/polling.md)                  |
| `refetchOnWindowFocus` | `focusRefetch()`     | `false` opts out. See [Window focus refetching](https://raf-query.katt.dev/docs/window-focus-refetching.md) |
| `refetchOnReconnect`   | `reconnectRefetch()` | `false` opts out                                                              |

## Writing a plugin

`plugin()` makes a plugin. A plugin contributes any of four things, and each takes effect in its own place:

<figure class="doc-diagram">
<svg viewBox="0 0 780 324" role="img" aria-labelledby="plugin-anatomy-title">
<title id="plugin-anatomy-title">What a plugin has, and where each piece takes effect</title>
<defs><marker id="plugin-anatomy-arrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="arrowhead" d="M1 1L9 5L1 9z"/></marker></defs>
<text class="head" x="20" y="24">A plugin has</text><text class="head" x="300" y="24">Where it takes effect</text>
<rect class="box" x="20" y="40" width="210" height="56" rx="8"/>
<text class="code" x="34" y="63">options</text>
<text class="note" x="34" y="82">declares the per-query options it reads</text>
<path class="arrow" d="M230 68H294" marker-end="url(#plugin-anatomy-arrow)"/>
<rect class="box" x="300" y="40" width="460" height="56" rx="8"/>
<text class="code" x="314" y="63">queryOptions({ retry: 1, … })</text>
<text class="note" x="314" y="82">a bound builder takes the option, typed</text>
<rect class="box" x="20" y="112" width="210" height="56" rx="8"/>
<text class="code" x="34" y="135">context</text>
<text class="note" x="34" y="154">values for every queryFn</text>
<path class="arrow" d="M230 140H294" marker-end="url(#plugin-anatomy-arrow)"/>
<rect class="box" x="300" y="112" width="460" height="56" rx="8"/>
<text class="code" x="314" y="135">queryFn: ({ api, signal }) =&gt; …</text>
<text class="note" x="314" y="154">the queryFn gets them, for the client or per request</text>
<rect class="box" x="20" y="184" width="210" height="56" rx="8"/>
<text class="code" x="34" y="207">link</text>
<text class="note" x="34" y="226">wraps every request</text>
<path class="arrow" d="M230 212H294" marker-end="url(#plugin-anatomy-arrow)"/>
<rect class="box" x="300" y="184" width="460" height="56" rx="8"/>
<text class="code" x="314" y="207">load → link → link → queryFn</text>
<text class="note" x="314" y="226">outermost first, in the order of the plugins array</text>
<rect class="box" x="20" y="256" width="210" height="56" rx="8"/>
<text class="code" x="34" y="279">setup</text>
<text class="note" x="34" y="298">a cache-wide behavior</text>
<path class="arrow" d="M230 284H294" marker-end="url(#plugin-anatomy-arrow)"/>
<rect class="box" x="300" y="256" width="460" height="56" rx="8"/>
<text class="code" x="314" y="279">&lt;QueryClientProvider client={…}&gt;</text>
<text class="note" x="314" y="298">started when a provider mounts the client; never on a server</text>
</svg>
<figcaption>What a plugin has, and where each piece takes effect.</figcaption>
</figure>

| Piece           | What it is                                     | Where it takes effect                                                          |
| --------------- | ---------------------------------------------- | ------------------------------------------------------------------------------ |
| **link**        | A function that wraps a request                | Around every request the client makes, the `queryFn` innermost                 |
| **`setup`**     | A function that makes the plugin a **feature** | Across the cache, from when a provider mounts the client until it unmounts     |
| **`context`**   | An object, or values its link adds per request | In every `queryFn` of the client, beside `client`, `queryKey` and `signal`     |
| **declaration** | An interface with `options` and `context`      | In the types: what factories and `defaults` can set, and what a `queryFn` gets |

A plugin with no link, `setup` or `context` only declares options.

The declaration is `plugin()`'s type argument: an interface with the `options` the plugin reads and the `context` it gives. Both are optional. It types the link's `op.options`, and a plugin that declares a `context` has to give it.

### A link

A link gets the request as `op` and calls `next(op)` to run the rest of the chain, like a [tRPC link](https://trpc.io/docs/client/links). The last link is the query's own `queryFn`. `op.options` has the query's options, over the client's [defaults](#client-wide-defaults), with the fields the plugin declares typed. `retry()` and `timeout(ms)` are plugins with a link.

```ts
import { plugin } from "@raf-query/react";

interface ErrorToasts {
	readonly options: { readonly errorMessage?: string };
}

// One toast per failed request, with the query's own message.
const errorToasts = plugin<ErrorToasts>({
	link: async (op, next) => {
		try {
			return await next(op);
		} catch (error) {
			toast.error(op.options.errorMessage ?? "Something went wrong");
			throw error;
		}
	},
});
```

### A feature

`setup(client, signal)` runs when a provider mounts the client, and `signal` aborts when the last provider of that client unmounts. So a feature runs once however many providers share the client, and never during a server render. `focusRefetch()`, `reconnectRefetch()` and `polling()` are features. This one listens to the server with an [`EventSource`](https://developer.mozilla.org/en-US/docs/Web/API/EventSource):

```ts
import { invalidateAll } from "@raf-query/react";

// Refetches what's on screen when the server says something changed.
const liveUpdates = plugin({
	setup: (client, signal) => {
		const events = new EventSource("/api/events");
		events.addEventListener("message", () => void invalidateAll(client));
		signal.addEventListener("abort", () => events.close());
	},
});
```

### Context for every queryFn

A plugin's `context` is merged into the context of every `queryFn` the client runs, beside `client`, `queryKey` and `signal`. The declaration names its fields:

```ts
interface Api {
	readonly context: { readonly api: ApiClient };
}

// A function, so each client is given its own API client.
const api = (apiClient: ApiClient) =>
	plugin<Api>({ context: { api: apiClient } });
```

A server makes one client per request, so a client's context belongs to that request: an API client that sends the request's cookies, a database reader for the signed-in user.

In a factory built with the `queryOptions` [bound to that client](#typing-options-by-the-client), the `queryFn` gets `api`, typed:

```tsx
export function postQuery(input: { slug: string }) {
	return queryOptions({
		queryKey: posts("bySlug", input.slug),
		queryFn: ({ api, signal }) => api.getPost(input.slug, { signal }),
	});
}
```

### Context per request

A plugin can also give its context from its link, for values that belong to one request: a token that may need refreshing, a trace id. The link passes `next` an operation with the `context` it adds for the `queryFn` and the links after it. It goes over what the plugins before it gave (`op.context`), so a link can add a field or replace one, and the fields it leaves out stay:

```ts
import { plugin } from "@raf-query/react";

interface Session {
	readonly context: { readonly token: string };
}

// No `context` here: the link gives it, to every request.
const session = plugin<Session>({
	link: async (op, next) =>
		next({ ...op, context: { ...op.context, token: await freshToken() } }),
});
```

The declaration is the same, so a factory reads `token` the same way:

```ts
import { bindQueryOptions, createQueryClient } from "@raf-query/react";

const makeQueryClient = () => createQueryClient({ plugins: [session] });
const queryOptions = bindQueryOptions<typeof makeQueryClient>();

export function draftsQuery() {
	return queryOptions({
		queryKey: posts("drafts"),
		queryFn: ({ token, signal }) => getDrafts(token, { signal }),
	});
}
```

A plugin that declares a context gives it one of the two ways. With no `context`, its link's `next` only takes an operation that has the declared fields, so this is a type error:

```ts
plugin<Session>({ link: (op, next) => next(op) });
```

A link can replace a field another plugin gave the client, too, for the one request. A paged query's pages are one request: they share its context.

### Options only

A plugin without a link, a `setup` or a `context` does nothing at runtime. It declares options: your app's own facts about a query, for [targets to match on](#selecting-queries-by-options). [Tags](https://raf-query.katt.dev/docs/query-invalidation.md#tags) are built this way.

```ts
export interface Ownership {
	readonly options: { readonly owner?: "editorial" | "community" };
}

// No link, setup or context: it only declares `owner`.
const ownership = plugin<Ownership>();
```

### The client's plugins

`createQueryClient` takes the plugins as one array. `recommended()` returns an array of plugins, so spread it among your own:

```ts
import { createQueryClient, recommended } from "@raf-query/react";

export function makeQueryClient(apiClient: ApiClient) {
	return createQueryClient({
		plugins: [
			errorToasts,
			...recommended(),
			liveUpdates,
			api(apiClient),
			ownership,
		],
	});
}
```

Links wrap each request in array order, outermost first: `errorToasts` comes before `retry()`, so it sees a request's error only after its retries ran out. Order matters for links only, unless two plugins give the same context field: then the later plugin's wins.

A package that ships a plugin needs only these exports: `plugin`, the types `Plugin` and `Operation` (the request a link gets) to name what it returns and takes, and `Target` and `QueryInfo` for a [target](https://raf-query.katt.dev/docs/query-invalidation.md#matching-with-where) that matches on the options it declares.

## Typing options by the client

A client's plugins decide what its queries can set and what their `queryFn`s get, so a builder always belongs to a client. `@raf-query/react` exports no `queryOptions` of its own: it exports binders, and an app binds its builders to its client once, in a file of their own. Every factory imports them from there:

```tsx title="src/raf.ts"
import {
	bindInfiniteQueryOptions,
	bindQueryOptions,
	bindUseQueryClient,
} from "@raf-query/react";

// `makeQueryClient` is the function above, imported with `import type`.
type Client = typeof makeQueryClient;

export const queryOptions = bindQueryOptions<Client>();
export const useQueryClient = bindUseQueryClient<Client>();
// Only in an app that pages:
export const infiniteQueryOptions = bindInfiniteQueryOptions<Client>();
```

<figure class="doc-diagram">
<svg viewBox="0 0 780 364" role="img" aria-labelledby="binding-title">
<title id="binding-title">How a builder is bound, in an app and in a library, and which clients run its factories</title>
<defs><marker id="binding-arrow" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="arrowhead" d="M1 1L9 5L1 9z"/></marker></defs>
<text class="head" x="20" y="24">In an app</text>
<rect class="box" x="20" y="40" width="360" height="56" rx="8"/>
<text class="code" x="34" y="63">makeQueryClient()</text>
<text class="note" x="34" y="82">plugins: [retry(), api(), ownership]</text>
<path class="arrow" d="M200 96V118" marker-end="url(#binding-arrow)"/>
<rect class="box" x="20" y="124" width="360" height="56" rx="8"/>
<text class="code" x="34" y="147">bindQueryOptions&lt;typeof makeQueryClient&gt;()</text>
<text class="note" x="34" y="166">in raf.ts, once per client</text>
<path class="arrow" d="M200 180V202" marker-end="url(#binding-arrow)"/>
<rect class="box" x="20" y="208" width="360" height="56" rx="8"/>
<text class="code" x="34" y="231">postQuery</text>
<text class="note" x="34" y="250">may set retry and owner; its queryFn gets api</text>
<path class="arrow" d="M200 264V286" marker-end="url(#binding-arrow)"/>
<rect class="box result" x="20" y="292" width="360" height="56" rx="8"/>
<text class="code" x="34" y="315">runs on a client with all three</text>
<text class="note" x="34" y="334">not on a client made without api()</text>
<text class="head" x="400" y="24">In a library</text>
<rect class="box" x="400" y="40" width="360" height="56" rx="8"/>
<text class="code" x="414" y="63">interface Convex { context: … }</text>
<text class="note" x="414" y="82">the declaration of the library's plugin</text>
<path class="arrow" d="M580 96V118" marker-end="url(#binding-arrow)"/>
<rect class="box" x="400" y="124" width="360" height="56" rx="8"/>
<text class="code" x="414" y="147">bindQueryOptions&lt;Convex &amp; Optional&lt;Retry&gt;&gt;()</text>
<text class="note" x="414" y="166">names the plugins its factories need</text>
<path class="arrow" d="M580 180V202" marker-end="url(#binding-arrow)"/>
<rect class="box" x="400" y="208" width="360" height="56" rx="8"/>
<text class="code" x="414" y="231">convexQuery(ref)</text>
<text class="note" x="414" y="250">its queryFn gets convex; sets retry where there is one</text>
<path class="arrow" d="M580 264V286" marker-end="url(#binding-arrow)"/>
<rect class="box result" x="400" y="292" width="360" height="56" rx="8"/>
<text class="code" x="414" y="315">runs on any client with convex()</text>
<text class="note" x="414" y="334">with or without retry()</text>
</svg>
<figcaption>A builder is bound to a client in an app, or to plugin declarations in a library. Its factories run on the clients that have those plugins.</figcaption>
</figure>

The types flow one way. The client factory lists the plugins, the binders read that list from the factory's type, the builders they return type every factory, and a factory then runs on the clients that have those plugins.

Each binder takes the type of the function that makes the client, or of the client. Only the type is read, so `import type` is enough and the factories don't import the client. A binder returns the plain builder, typed for the client: binding costs a few bytes, and an app that doesn't page leaves out `bindInfiniteQueryOptions` and ships none of the paging code.

Factories built with the bound builders never name the client:

```tsx
export function commentsQuery(input: { slug: string }) {
	return infiniteQueryOptions({
		queryKey: comments(input.slug),
		// `api` is the context the `api()` plugin gives
		queryFn: ({ api, pageParam, signal }) =>
			api.listComments({ cursor: pageParam, slug: input.slug }, { signal }),
		initialPageParam: 0,
		getNextPageParam: (lastPage) => lastPage.nextCursor,
		// Options the client's plugins declare
		errorMessage: "Couldn't load the comments",
		owner: "community",
		retry: 1,
	});
}
```

- They take the options the client's plugins declare, with their types. Anything else is a type error:

```tsx
queryOptions({ queryKey: account("me"), queryFn: getMe, cacheFor: 60_000 });
```

- Their `queryFn` gets the context the client's plugins give.
- Verbs such as `invalidateMany` and `setData`, and `load` for each of its entries, take them only with a client that has those plugins. The bound `useQueryClient` returns the app's client, so verbs called in components take the app's factories:

```tsx
import { invalidateMany } from "@raf-query/react";

export function RefreshComments(props: { slug: string }) {
	const client = useQueryClient();
	return (
		<button
			onClick={() => invalidateMany(client, commentsQuery, props)}
			type="button"
		>
			Refresh
		</button>
	);
}
```

- `where` targets see the client's options, as [Selecting queries by options](#selecting-queries-by-options) shows.

The bare `QueryClient` type stands for any client, whatever its plugins. Verbs and `load` given one take the factories and targets that need no plugin, and reject the rest. The `useQueryClient` that `@raf-query/react` exports returns that type, which is why components get the client from the bound one. Wherever your app names its client's type, write `ReturnType<typeof makeQueryClient>`: TanStack Router's [router context](https://tanstack.com/router/latest/docs/framework/react/guide/router-context), a React Router [context](https://reactrouter.com/api/utils/createContext), a helper's parameter. `ClientFor<typeof factory>` is any client that runs that factory:

```tsx
import type { ClientFor } from "@raf-query/react";

// The app's client
type AppQueryClient = ReturnType<typeof makeQueryClient>;

// Any client that can run `commentsQuery`
type CommentsClient = ClientFor<typeof commentsQuery>;

export function refreshComments(client: CommentsClient, slug: string) {
	return invalidateMany(client, commentsQuery, { slug });
}
```

A binder takes the type of a function, not of a client at module level, because a server makes one client per request. It's the same idea as a [tRPC v12](https://github.com/trpc/trpc/tree/v12) client typing its call options from its links.

### Several clients

Nothing is registered globally, so a program can have several clients with different plugins. A client runs a factory when it has **at least** the plugins the factory's builder is bound to. Bind a builder to one client for the factories only it runs, and to the plugins several clients share, named by their declarations, for the factories they all run. `Retry`, `Polling`, `FocusRefetch` and `ReconnectRefetch` are the declarations of the built-in plugins; intersect them to name more than one (`Retry & Polling`).

```ts
import {
	bindQueryOptions,
	createQueryClient,
	polling,
	type Retry,
	retry,
} from "@raf-query/react";

// The site retries and polls; the embeddable widget only retries.
export const makeSiteClient = () =>
	createQueryClient({ plugins: [retry(), polling()] });
export const makeWidgetClient = () => createQueryClient({ plugins: [retry()] });

// Bound to the site's client: its factories need `retry()` and `polling()`.
const siteQueryOptions = bindQueryOptions<typeof makeSiteClient>();
// Bound to the plugin both clients have: its factories run on either.
const sharedQueryOptions = bindQueryOptions<Retry>();

export function postViewsQuery(input: { slug: string }) {
	return siteQueryOptions({
		queryKey: posts("views", input.slug),
		queryFn: () => getPostViews(input.slug),
		refetchInterval: 2000,
	});
}

export function postQuery(input: { slug: string }) {
	return sharedQueryOptions({
		queryKey: posts("bySlug", input.slug),
		queryFn: () => getPost(input.slug),
		retry: 1,
	});
}
```

Each client runs the shared factory, and only the site's client runs the one that polls. The last call is a type error:

```ts
import { invalidateMany } from "@raf-query/react";

const site = makeSiteClient();
const widget = makeWidgetClient();

await invalidateMany(site, postQuery);
await invalidateMany(widget, postQuery);
await invalidateMany(site, postViewsQuery);
await invalidateMany(widget, postViewsQuery);
```

### Options several factories share

`OptionsOf<typeof makeQueryClient>` is what the client's builders let a query set beside its key and `queryFn`: the core's options and those of the client's plugins. Use it to type a fragment that several factories spread:

```tsx
import type { OptionsOf } from "@raf-query/react";

// For data that doesn't change: never stale, and not worth a retry
const pinned = {
	retry: false,
	staleTime: Infinity,
} satisfies OptionsOf<typeof makeQueryClient>;

export function authorQuery(input: { id: string }) {
	return queryOptions({
		...pinned,
		queryKey: authors(input.id),
		queryFn: () => getAuthor(input.id),
	});
}
```

## Client-wide defaults

`defaults` sets an option for every query of the client: the core's `staleTime`, `gcTime` and `structuralSharing`, and any option the client's plugins declare. A query's own option wins.

```ts
import { recommended } from "@raf-query/react";

export function makeQueryClient() {
	return createQueryClient({
		plugins: recommended(),
		defaults: {
			// The core's options
			staleTime: 30_000,
			gcTime: 10 * 60_000,
			// Options of `retry()` and `focusRefetch()`
			retry: 1,
			refetchOnWindowFocus: false,
		},
	});
}
```

`defaults` is typed by the `plugins` of the same call, so a default for an option no plugin declares is an error:

```ts
createQueryClient({
	plugins: [polling()],
	defaults: { retry: 1 },
});
```

## Selecting queries by options

A `where` target picks queries by what their options say. Written inline, `query.options` has the options of the client the verb is called with:

```ts
import { invalidateMany } from "@raf-query/react";

const qc = makeQueryClient(apiClient);

await invalidateMany(qc, {
	where: (query) => query.options.owner === "community",
	// (property) owner: "editorial" | "community" | undefined
});
```

A target kept in a variable is typed `Target<TOptions, TParam>`, by the options it reads and the parameter it takes:

```ts
import type { RootOf, Target } from "@raf-query/react";

type Team = NonNullable<Ownership["options"]["owner"]>;

// `owner` the way a client with `ownership` has it: present, possibly `undefined`
type Owned = RootOf<Ownership>["options"];

const ownedBy: Target<Owned, Team> = {
	where: (query, team) => query.options.owner === team,
};

await invalidateMany(qc, ownedBy, "editorial");
```

`RootOf<Ownership>["options"]` is `owner` the way a client with the plugin has it: present, and possibly `undefined`. Typed that way, `ownedBy` fits only clients made with `ownership`. Typed `Target<Ownership["options"], Team>`, where `owner` is optional, it would also fit a client without the plugin, and match nothing there.

See [Query invalidation](https://raf-query.katt.dev/docs/query-invalidation.md#matching-with-where) for targets, and for tags, which are targets over an option.

## Binding a library to plugins

A package that ships factories can't name the app's client. It binds its builders to the declarations of the plugins its factories need. `Optional<…>` names a plugin they don't need: its options can be set, and they take effect on the clients that have the plugin.

```ts
import {
	bindQueryOptions,
	group,
	type Optional,
	type Plugin,
	plugin,
	type Retry,
} from "@raf-query/react";

export interface CmsClient {
	entry(id: string, init: { signal: AbortSignal }): Promise<{ title: string }>;
}

// What the package's plugin declares: a client for every `queryFn`
export interface Cms {
	readonly context: { readonly cms: CmsClient };
}

export function cms(client: CmsClient): Plugin<Cms> {
	return plugin<Cms>({ context: { cms: client } });
}

// The package's own builder: its factories need `cms()`, and set `retry`
// on the clients that have `retry()`.
const queryOptions = bindQueryOptions<Cms & Optional<Retry>>();

const entries = group("cms");

export function entryQuery(input: { id: string }) {
	return queryOptions({
		queryKey: entries(input.id),
		queryFn: ({ cms, signal }) => cms.entry(input.id, { signal }),
		// The CMS client retries on its own
		retry: false,
	});
}
```

The app gives its client the package's plugin, and the package's factories run on it. On a client without the plugin, here the last one, they're a type error:

```ts
import { invalidateOne } from "@raf-query/react";

// With `retry()`, which reads the query's `retry: false`
const retrying = createQueryClient({ plugins: [retry(), cms(cmsClient)] });
await invalidateOne(retrying, entryQuery, { id: "home" });

// Without it: the option does nothing
const plain = createQueryClient({ plugins: [cms(cmsClient)] });
await invalidateOne(plain, entryQuery, { id: "home" });

const withoutCms = createQueryClient({ plugins: [retry()] });
await invalidateOne(withoutCms, entryQuery, { id: "home" });
```

A package whose factories need no plugin calls `bindQueryOptions()` without a type argument. That builder takes the core's options only (`staleTime`, `gcTime`, `structuralSharing`, `ssr`), its `queryFn` gets `client`, `queryKey` and `signal`, and its factories run on any client:

```ts
import { bindQueryOptions, group } from "@raf-query/react";

// No type argument: the builder takes the core's options only, and its
// factories run on any client.
const queryOptions = bindQueryOptions();

const status = group("status-page");

export function incidentsQuery() {
	return queryOptions({
		queryKey: status("incidents"),
		queryFn: ({ signal }) => listIncidents({ signal }),
		staleTime: 60_000,
	});
}

queryOptions({
	queryKey: status("incidents", "retried"),
	queryFn: ({ signal }) => listIncidents({ signal }),
	retry: 1,
});
```

## Serialization

Options aren't sent with dehydrated state during SSR: they come from the factory, so they can hold anything, functions included. An entry only hydrated, which nothing has read through its factory yet, has `{}` as its options until it's read. Invalidations still reach it: they're checked again when the entry is next read.

A plugin's context isn't sent either. Each client has its own, from the plugins it was made with.
