npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@beignet/react-query

v0.0.52

Published

TanStack Query integration for Beignet

Readme

@beignet/react-query

Runtime: Beignet requires Node.js 22.12 or newer. Bun is optional.

TanStack Query integration for Beignet

[!CAUTION] Beignet is experimental alpha software. The 0.0.x package line is for early evaluation, and APIs may change between releases while the framework settles.

This package provides options-first TanStack Query integration that's automatically typed based on your contracts. Generate queryOptions, mutationOptions, and infiniteQueryOptions that work with all TanStack Query primitives (useQuery, useMutation, useInfiniteQuery, prefetchQuery, fetchQuery, etc.) with full type inference.

Installation

npm install @beignet/react-query @beignet/core @tanstack/react-query react

TypeScript requirements

This package requires TypeScript 5.0 or higher for proper type inference.

Agent skills

This package ships a TanStack Intent skill for coding agents: @beignet/react-query#client. Load it when adding typed client setup, React Query options, infinite queries, feature client helpers, hooks, cache keys, cache invalidation, server prefetching, idempotent mutations, or client/server boundary fixes in a Beignet app.

Setup

1. Create your app client helpers

import { createClient } from "@beignet/core/client";
import { createReactQuery } from "@beignet/react-query";
import { QueryClient } from "@tanstack/react-query";

export const apiClient = createClient({
  baseUrl: "https://api.example.com",
  headers: async () => ({
    Authorization: `Bearer ${getToken()}`,
  }),
});

export const rq = createReactQuery(apiClient);

export function makeQueryClient() {
  return new QueryClient();
}

2. Set up QueryClientProvider

// app/providers.tsx
import { QueryClientProvider } from "@tanstack/react-query";
import { type ReactNode, useState } from "react";
import { makeQueryClient } from "@/client";

export function Providers({ children }: { children: ReactNode }) {
  const [queryClient] = useState(() => makeQueryClient());

  return (
    <QueryClientProvider client={queryClient}>
      {children}
    </QueryClientProvider>
  );
}

3. Add feature client helpers

Keep root client/ for shared adapter setup, then put feature-specific query options, mutation options, invalidation helpers, and hooks under features/<feature>/client/:

// features/todos/client/queries.ts
import type { QueryClient } from "@tanstack/react-query";
import { rq } from "@/client";
import { createTodo, listTodos } from "@/features/todos/contracts";

export function listTodosQueryOptions() {
  return rq(listTodos).queryOptions({ query: {} });
}

export function createTodoMutationOptions() {
  return rq(createTodo).mutationOptions();
}

export function invalidateTodos(queryClient: QueryClient) {
  return rq(listTodos).invalidate(queryClient);
}

Components can import those helpers and keep UI state separate from cache-key construction:

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
  createTodoMutationOptions,
  invalidateTodos,
  listTodosQueryOptions,
} from "@/features/todos/client/queries";

function TodoList() {
  const queryClient = useQueryClient();
  const todosQuery = useQuery(listTodosQueryOptions());
  const createTodoMutation = useMutation({
    ...createTodoMutationOptions(),
    onSuccess: () => invalidateTodos(queryClient),
  });

  return <div>{/* ... */}</div>;
}

Usage

Options-first API (recommended)

The options-first API generates options objects that can be used with any TanStack Query primitive.

Query options

import { useQuery } from "@tanstack/react-query";
import { rq } from "@/client";
import { getTodo } from "@/features/todos/contracts";

function TodoDetail({ id }: { id: string }) {
  // Generate query options
  const todoQuery = rq(getTodo).queryOptions({
    path: { id },
    staleTime: 30_000,
  });

  // Use with any TanStack Query primitive
  const { data, isLoading, error } = useQuery(todoQuery);

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h1>{data.title}</h1>
      <p>Completed: {data.completed ? "Yes" : "No"}</p>
    </div>
  );
}

Prefetching

import { useQueryClient } from "@tanstack/react-query";
import { rq } from "@/client";
import { getTodo } from "@/features/todos/contracts";

function TodoList() {
  const queryClient = useQueryClient();

  const handleHover = (id: string) => {
    // Prefetch on hover using queryOptions
    const todoQuery = rq(getTodo).queryOptions({
      path: { id },
    });
    
    queryClient.prefetchQuery(todoQuery);
  };

  return <div>{/* ... */}</div>;
}

Server-side data fetching

import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
import { makeQueryClient, rq } from "@/client";
import { getTodo } from "@/features/todos/contracts";

export async function TodoPage({ params }: { params: { id: string } }) {
  const queryClient = makeQueryClient();

  // Fetch on the server
  const todoQuery = rq(getTodo).queryOptions({
    path: { id: params.id },
  });

  await queryClient.prefetchQuery(todoQuery);

  return (
    <HydrationBoundary state={dehydrate(queryClient)}>
      <TodoDetail id={params.id} />
    </HydrationBoundary>
  );
}

That prefetch path uses the generated HTTP query function. In Next.js apps, ordinary { contract, useCase } routes can avoid an internal HTTP request by using a cached server-context helper plus a server-only prefetch helper that preserves the contract query key and replaces only the server queryFn:

import { getTodoUseCase } from "@/features/todos/use-cases";
import { getAppRequestContext } from "@/lib/server-context";
import { serverUseCaseQueryOptions } from "@/lib/server-react-query";

const ctx = await getAppRequestContext();
const queryClient = makeQueryClient();

await queryClient.prefetchQuery(
  serverUseCaseQueryOptions(
    rq(getTodo).queryOptions({ path: { id: params.id } }),
    getTodoUseCase,
    ctx,
    { id: params.id },
  ),
);

Use the use-case path only when the use case output is the contract success body. Use the HTTP rq(...) path when the route handler owns response mapping, headers, streaming, or other HTTP-layer behavior.

Mutation options

import { useMutation, useQueryClient } from "@tanstack/react-query";
import { rq } from "@/client";
import { createTodo, listTodos } from "@/features/todos/contracts";

function CreateTodoForm() {
  const queryClient = useQueryClient();

  // Generate mutation options
  const createTodoMutation = rq(createTodo).mutationOptions({
    onSuccess: (data, vars, onMutateResult, context) => {
      // Invalidate every cached listTodos call.
      rq(listTodos).invalidate(queryClient);
    },
  });

  const mutation = useMutation(createTodoMutation);

  const handleSubmit = (data: { title: string }) => {
    mutation.mutate({ body: data });
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* form fields */}
      <button disabled={mutation.isPending}>
        {mutation.isPending ? "Creating..." : "Create Todo"}
      </button>
    </form>
  );
}

Infinite query options

For contracts that follow the Beignet cursor pagination convention — an optional cursor query param and a PageResult response with page.nextCursor — spread cursorPagination() into the options:

import { useInfiniteQuery } from "@tanstack/react-query";
import { cursorPagination } from "@beignet/react-query";
import { rq } from "@/client";
import { listTodos } from "@/features/todos/contracts";

function InfiniteTodoList() {
  const todosInfiniteQuery = rq(listTodos).infiniteQueryOptions({
    query: { status: "open" },
    ...cursorPagination(),
  });

  const { data, fetchNextPage, hasNextPage, isFetchingNextPage } =
    useInfiniteQuery(todosInfiniteQuery);

  return (
    <div>
      {data?.pages.map((page) =>
        page.items.map((todo) => <div key={todo.id}>{todo.title}</div>)
      )}
      
      <button
        onClick={() => fetchNextPage()}
        disabled={!hasNextPage || isFetchingNextPage}
      >
        {isFetchingNextPage ? "Loading more..." : "Load More"}
      </button>
    </div>
  );
}

data.pages is typed per page: the infinite options observe InfiniteData of the contract response. Contracts without a cursor query param or without page.nextCursor in the response fail to typecheck at the spread site.

Contracts that paginate differently pass initialPageParam, getNextPageParam, and page(...) by hand:

const todosInfiniteQuery = rq(listTodos).infiniteQueryOptions({
  query: { limit: 10 },
  initialPageParam: 0,
  page: ({ pageParam }) => ({
    query: { offset: pageParam },
  }),
  getNextPageParam: (lastPage) =>
    lastPage.page.hasMore
      ? lastPage.page.offset + lastPage.items.length
      : undefined,
});

API reference

createReactQuery(client, options?)

Creates a React Query adapter factory.

const rq = createReactQuery(apiClient);

Headers are excluded from generated query keys by default because persisted caches would otherwise store credentials such as Authorization tokens. When a non-secret request-shaping header changes response data, opt that specific header into keys with keyHeaders:

const rq = createReactQuery(apiClient, {
  keyHeaders: ["X-Workspace-Preview"],
});

rq(listTodos).queryOptions({
  headers: { "X-Workspace-Preview": "workspace-1", Authorization: "Bearer ..." },
});
// queryKey: ["beignet", "todos", "listTodos", "GET /todos",
//   { headers: { "x-workspace-preview": "workspace-1" } }]

Only whitelisted header names are included. Names are matched case-insensitively and stored lowercased in the key. Never whitelist credential headers; pass a per-call key when you need a fully custom key instead.

rq(contract)

Creates a contract helper with query/mutation options methods.

const helper = rq(getTodo);

helper.queryOptions(options)

[Recommended] Generate query options that can be passed to any TanStack Query primitive.

const queryOpts = helper.queryOptions({
  path: { ... },            // Required when the contract has required path params
  query?: { ... },          // Required when the contract has required query params
  body?: { ... },           // Required when the contract has a required body
  headers?: { ... },        // Sent with the request; keyed only via keyHeaders
  key?: readonly unknown[], // Custom query key
  // ...any other TanStack Query options (staleTime, enabled, select, etc.)
});

// Use with any primitive
useQuery(queryOpts);
queryClient.prefetchQuery(queryOpts);
queryClient.fetchQuery(queryOpts);
queryClient.ensureQueryData(queryOpts);

select threads through the options, so the observed data narrows while the generated queryFn still returns and caches the raw contract response:

const { data } = useQuery(
  rq(getTodo).queryOptions({
    path: { id: "123" },
    select: (todo) => todo.title,
  }),
);
// data is typed as: string | undefined

helper.mutationOptions(options)

[Recommended] Generate mutation options that can be passed to useMutation.

const mutationOpts = helper.mutationOptions({
  // ...any TanStack Query mutation options (onSuccess, onError, retry, etc.)
});

useMutation(mutationOpts);

For contracts with idempotency metadata, the generated mutationFn derives one idempotency key per variables object and keeps it stable across TanStack retry attempts, so retried requests replay instead of re-executing. Fresh variables objects passed to separate mutate(...) calls get distinct keys. Retry state is keyed by variables-object identity, so reusing the exact same object for a later intentional mutation also reuses its key. Pass idempotencyKey in the mutation variables when multiple invocations should be one logical command:

mutation.mutate({ body: { title: "New todo" }, idempotencyKey: key });

Caveat: calling mutate() with no variables skips per-invocation key derivation and the client generates a fresh key per attempt. Pass a variables object when an idempotent mutation should keep its key across retries.

helper.infiniteQueryOptions(options)

[Recommended] Generate infinite query options for pagination. The options observe InfiniteData of the contract response, so useInfiniteQuery data has typed pages, and select narrows the observed data the same way as queryOptions.

For contracts that follow the cursor convention, spread cursorPagination():

const infiniteOpts = rq(listTodos).infiniteQueryOptions({
  query: { status: "open" },
  ...cursorPagination(),
});

useInfiniteQuery(infiniteOpts);

For other pagination shapes, pass the page-param options by hand:

const infiniteOpts = helper.infiniteQueryOptions({
  path?: { ... },          // Static path params included in the cache key
  query?: { ... },         // Static query params included in the cache key
  body?: { ... },          // Static body fields included in the cache key
  page?: (ctx: { pageParam }) => ({
    path?: { ... },        // Page-specific path params
    query?: { ... },       // Page-specific query params (cursor, offset, etc.)
    body?: { ... },        // Page-specific body fields (cursor, offset, etc.)
  }),
  initialPageParam: ...,
  getNextPageParam: (lastPage) => ...,
  getPreviousPageParam: (firstPage) => ...,
  key?: readonly unknown[], // Optional custom query key
  // ...any other TanStack Query infinite query options
});

useInfiniteQuery(infiniteOpts);

For body-paginated contracts, such as a POST search endpoint, keep the stable filters in the static body and put the cursor in page(...).body. The static body is part of the cache key, and each page request sends the merged body:

const searchOpts = rq(searchTodos).infiniteQueryOptions({
  body: { term: "beignet" },
  page: ({ pageParam }) => ({
    body: { cursor: pageParam ?? null },
  }),
  initialPageParam: null as string | null,
  getNextPageParam: (lastPage) => lastPage.page.nextCursor ?? undefined,
});

If you need fully dynamic params, pass a custom key and use params(...) instead:

const infiniteOpts = helper.infiniteQueryOptions({
  key: ["todos", { status: "open" }],
  params: ({ pageParam }) => ({
    query: { status: "open", cursor: pageParam ?? null },
  }),
  initialPageParam: null,
  getNextPageParam: (lastPage) => lastPage.page.nextCursor ?? undefined,
});

cursorPagination()

Infinite-query options for contracts that follow the Beignet cursor pagination convention: an optional cursor query param on the request and a PageResult-style response with page.nextCursor (string | null). Spread the result into infiniteQueryOptions(...):

import { cursorPagination } from "@beignet/react-query";

useInfiniteQuery(
  rq(listTodos).infiniteQueryOptions({
    query: { status: "open" },
    ...cursorPagination(),
  }),
);

The first page is fetched without a cursor, each next page sends lastPage.page.nextCursor, and null tells TanStack Query there is no next page. Type safety is structural: contracts without a cursor query param or without page.nextCursor in the response fail to typecheck at the spread site.

helper.namespaceKey()

Generate a namespace-level key for broad cache operations. Contracts created from defineContractGroup().namespace("todos") use that namespace. Non-namespaced contracts use null so they cannot collide with a real namespace string.

helper.namespaceKey(); // ["beignet", "todos"]

helper.contractKey()

Generate a contract-level key without path, query, or body params. The key includes the contract route ("GET /todos/:id"), so two contracts with the same derived local name but different routes — for example /v1/todos and /v2/todos list contracts — never share a cache key.

helper.contractKey(); // ["beignet", "todos", "getTodo", "GET /todos/:id"]

The route segment is also exposed as helper.route ("GET /todos/:id").

helper.key(params?)

Generate a stable query key for cache operations.

helper.key();
// ["beignet", "todos", "getTodo", "GET /todos/:id"]
helper.key({ path: { id: "1" } });
// ["beignet", "todos", "getTodo", "GET /todos/:id", { path: { id: "1" } }]

key(...) normalizes transport params the same way the client serializes them: null and undefined path, query, and opted-in header entries are omitted, while meaningful values like 0, false, and empty strings are preserved. JSON request bodies have different semantics: null, empty objects, and null-valued object properties stay in the key, while an undefined body and undefined object properties are omitted. This keeps distinct JSON requests from sharing a cache entry. Headers are excluded unless the adapter opted in with createReactQuery(client, { keyHeaders }).

helper.namespaceFilter(options?)

Generate TanStack Query filters for every contract in the helper's Beignet namespace.

queryClient.invalidateQueries(helper.namespaceFilter());
queryClient.invalidateQueries(helper.namespaceFilter({ stale: true }));

helper.contractFilter(options?)

Generate TanStack Query filters for every cached call to this contract.

queryClient.invalidateQueries(helper.contractFilter());

helper.filter(params?, options?)

Generate TanStack Query filters for one contract call or parameter prefix.

queryClient.invalidateQueries(
  helper.filter({ path: { id: "1" } }, { exact: true }),
);

These filters wrap plain TanStack Query keys, so prefix invalidation works as expected while TanStack Query still owns cache behavior:

queryClient.invalidateQueries(rq(getTodo).namespaceFilter());
rq(getTodo).invalidate(queryClient);
rq(getTodo).invalidate(queryClient, { path: { id: "1" } });

Use the smallest filter that matches the data you want to refresh:

| Helper | Scope | | --- | --- | | namespaceFilter() | Every contract in one Beignet namespace. | | contractFilter() | Every cached call for one contract. | | filter({ path, query, body }) | One parameter-scoped contract key. |

helper.invalidate(queryClient, params?, options?)

Invalidate cached data for one contract using the helper's generated filters. With no params it invalidates every cached call to the contract. Pass params to target a detail key or parameter prefix.

await rq(listTodos).invalidate(queryClient);
await rq(getTodo).invalidate(queryClient, { path: { id: "1" } });

For list writes, invalidate the contract key so every filtered or paginated list result refreshes:

const createTodoMutation = useMutation(
  rq(createTodo).mutationOptions({
    onSuccess: () => {
      rq(listTodos).invalidate(queryClient);
    },
  }),
);

For detail writes, update or invalidate the exact detail key and then invalidate affected list contracts:

const updateTodoMutation = useMutation(
  rq(updateTodo).mutationOptions({
    onSuccess: (_todo, vars) => {
      rq(getTodo).invalidate(queryClient, { path: vars.path });
      rq(listTodos).invalidate(queryClient);
    },
  }),
);

helper.endpoint

Access the underlying endpoint for manual calls.

const data = await helper.endpoint.call({ path: { id: "123" } });

Type inference

All options are fully typed based on your contracts:

const { data } = useQuery(rq(getTodo).queryOptions({ path: { id: "123" } }));
// data is typed as: { id: string; title: string; completed: boolean }

const mutation = useMutation(rq(createTodo).mutationOptions());
mutation.mutate({ body: { title: "New Todo" } });
// body is typed as: { title: string; completed?: boolean }

Error handling

React Query errors are typed from the endpoint contract, including declared catalog errors and non-2xx response bodies:

const todo = rq(getTodo);
const { error } = useQuery(todo.queryOptions({ path: { id: "123" } }));

if (todo.endpoint.isError(error, { code: "TODO_NOT_FOUND" })) {
  console.log(error.details); // typed from the catalog details schema
} else if (error) {
  console.log(error.message);
}

Migration from hook-first API

If you were using the hook-first API, you can migrate to the options-first API:

Before (hook-first):

const { data } = rq(getTodo).useQuery({ path: { id } });

After (options-first):

const { data } = useQuery(rq(getTodo).queryOptions({ path: { id } }));

Hook wrappers have been removed—use the options-first API for all queries and mutations.

Related packages

License

MIT