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

@nkzw/fate

v1.6.0

Published

fate is a modern data client for React.

Readme

fate is a modern data client for React inspired by Relay and GraphQL. It combines view composition, normalized caching, data masking, Async React features, and type-safe data fetching.

Features

  • View Composition: Components declare their data requirements using co-located "views". Views are composed into a single request per screen, minimizing network requests and eliminating waterfalls.
  • Normalized Cache: fate maintains a normalized cache for all fetched data. This enables efficient data updates through actions and mutations and avoids stale or duplicated data.
  • Data Masking & Strict Selection: fate enforces strict data selection for each view, and masks (hides) data that components did not request. This prevents accidental coupling between components and reduces overfetching.
  • Async React: fate uses modern Async React features like Actions, Suspense, and use to support concurrent rendering and enable a seamless user experience.
  • Lists & Pagination: fate provides built-in support for connection-style lists with cursor-based pagination, making it easy to implement infinite scrolling and "load-more" functionality.
  • Optimistic Updates: fate supports declarative optimistic updates for mutations, allowing the UI to update immediately while the server request is in-flight. If the request fails, the cache and its associated views are rolled back to their previous state.
  • Live Views: fate can keep individual view refs up to date through a single native Server-Sent Events stream, merging updates into the normalized cache.
  • AI-Ready: fate's minimal, predictable API and explicit data selection enable local reasoning, enabling humans and AI tools to generate stable, type-safe data-fetching code.

A modern data client for React

fate is designed to make data fetching and state management in React applications more composable, declarative, and predictable. The framework has a minimal API, no DSL, and no magic—it's just JavaScript.

GraphQL and Relay introduced several novel ideas: fragments co‑located with components, a normalized cache keyed by global identifiers, and a compiler that hoists fragments into a single network request. These innovations made it possible to build large applications where data requirements are modular and self‑contained.

Nakazawa Tech builds apps and games primarily with GraphQL and Relay. We advocate for these technologies in talks and provide templates (server, client) to help developers get started quickly.

However, GraphQL comes with its own type system and query language. If you are already using tRPC or another type‑safe RPC framework, it's a significant investment to adopt and implement GraphQL on the backend. This investment often prevents teams from adopting Relay on the frontend.

Many React data frameworks lack Relay's ergonomics, especially fragment composition, co-located data requirements, predictable caching, and deep integration with modern React features. Optimistic updates usually require manually managing keys and imperative data updates, which is error-prone and tedious.

fate takes the great ideas from Relay and applies them to plain TypeScript data fetching. You get type safety between the client and server, a native protocol with optional adapters such as tRPC, and GraphQL-like ergonomics for data fetching. Using fate usually looks like this:

export const PostView = view<Post>()({
  author: UserView,
  content: true,
  id: true,
  title: true,
});

export const PostCard = ({ post: postRef }: { post: ViewRef<'Post'> }) => {
  const post = useView(PostView, postRef);

  return (
    <Card>
      <h2>{post.title}</h2>
      <p>{post.content}</p>
      <UserCard user={post.author} />
    </Card>
  );
};

Learn more about fate's core concepts or create an app from one of the templates.

Getting Started

Template

Create a new fate app with Vite+:

vp create fate my-app

Explore the fate stack to see the tools included in your new project.

The template selector can create a React or Vue client for a Void app with Drizzle, a tRPC app with Drizzle or Prisma, a GraphQL app with Prisma, or a fate client for an existing GraphQL server. React is the default UI framework; pass --framework vue or choose Vue in the template selector to create a Vue app. The template sources live in the fate repo under packages/create-fate/templates/fate. They feature modern tools to deliver an incredibly fast development experience.

Manual Installation

For a React client, install react-fate. It requires React 19.2+:

::: code-group

npm add react-fate
pnpm add react-fate
yarn add react-fate

:::

For a Vue client, install vue-fate:

::: code-group

npm add vue-fate
pnpm add vue-fate
yarn add vue-fate

:::

If your server is a separate package, install @nkzw/fate there as a runtime dependency too. Install @nkzw/fate on the client only for a barebones integration without a framework adapter:

::: code-group

npm add @nkzw/fate
pnpm add @nkzw/fate
yarn add @nkzw/fate

:::

[!WARNING]

fate is currently in alpha and not production ready. If something doesn't work for you, please open a pull request.

If you'd like to try the example app in GitHub Codespaces, click the button below:

Open in GitHub Codespaces

Core Concepts

fate has a minimal API surface and is aimed at reducing data fetching complexity.

Thinking in Views

In fate, each component declares the data it needs using views. Views are composed upward through the component tree until they reach a root, where the actual request is made. fate fetches all required data in a single request. React Suspense manages loading states, and any data-fetching errors naturally bubble up to React error boundaries. This eliminates the need for imperative loading logic or manual error handling.

Traditionally, React apps are built with components and hooks. fate introduces a third primitive: views – a declarative way for components to express their data requirements. An app built with fate looks more like this:

With fate, you no longer worry about when to fetch data, how to coordinate loading states, or how to handle errors imperatively. You avoid overfetching, stop passing unnecessary data down the tree, and eliminate boilerplate types created solely for passing server data to child components.

[!NOTE] Views in fate are what fragments are in GraphQL.

Views

Defining Views

Let's start by defining a simple view for a blog's Post component. fate requires you to explicitly "select" each field that you plan to use in your components. Here is how you can define a view for a Post entity that has title and content fields:

import { view } from 'react-fate';

type Post = {
  content: string;
  id: string;
  title: string;
};

export const PostView = view<Post>()({
  content: true,
  id: true,
  title: true,
});

Fields are selected by setting them to true in the view definition. This tells fate that these fields should be fetched from the server and made available to components that use this view.

[!NOTE] The Post type above is an example. In a real application, this type is defined on the server and imported into your client code.

Resolving a View with useView

Now we can use the view that we defined in a PostCard React component to resolve the data against a reference of an individual Post:

import { useView, ViewRef } from 'react-fate';

export const PostCard = ({ post: postRef }: { post: ViewRef<'Post'> }) => {
  const post = useView(PostView, postRef);

  return (
    <Card>
      <h2>{post.title}</h2>
      <p>{post.content}</p>
    </Card>
  );
};

A ViewRef is a reference to a concrete object of a specific type, for example a Post with id 7. It contains the unique ID of the object, the type name (as __typename) and some fate-specific metadata. fate creates and manages these references for you, and you can pass them around your components as needed.

Components using useView listen to changes for all selected fields. When data changes, fate re-renders all of the fields that depend on that data. For example, if the title of the Post changes, the PostCard component re-renders with new data. However, if a different field such as likes that isn't selected in PostView changes, the PostCard component will not re-render.

Fetching Data with useRequest

Now that we defined our view and component, we fetch the data from the server using the useRequest hook from fate. This hook allows us to declare what data we need for a specific screen or component tree. At the root of our app, we can request a list of posts like this:

import { useRequest } from 'react-fate';
import { PostCard, PostView } from './PostCard.tsx';

export function App() {
  const { posts } = useRequest({ posts: { list: PostView } });

  return posts.map((post) => <PostCard key={post.id} post={post} />);
}

Learn more about useRequest in the Requests Guide.

Composing Views

In the above example we are defining a single view for a Post. One of fate's core strengths is view composition. Let's say we want to show the author's name along with the post. A simple way to do this is by adding an author field to the PostView with a concrete selection:

import { Suspense } from 'react';
import { useView, ViewRef } from 'react-fate';

export const PostView = view<Post>()({
  author: {
    id: true,
    name: true,
  },
  content: true,
  id: true,
  title: true,
});

const PostCard = ({ postRef }: { postRef: ViewRef<'Post'> }) => {
  const post = useView(PostView, postRef);
  return (
    <Card>
      <h2>{post.title}</h2>
      <p>by {post.author.name}</p>
      <p>{post.content}</p>
    </Card>
  );
};

This code fetches the author associated with the Post and makes it available to the PostCard component. However, this approach has some downsides:

  1. The author selection is tightly coupled to the PostView. If we want to use the author's data in another component, we would need to duplicate the field selection.
  2. If the author has more fields that we want to use in other components, we would need to add them to the PostView, leading to overfetching.
  3. We cannot reuse the author field selection in other views or components.

In fate, views are composable and reusable. Instead of inlining the selection, we can define a UserView and compose it into the PostView like this:

import type { Post, User } from '@your-org/server/views';
import { view } from 'react-fate';

export const UserView = view<User>()({
  id: true,
  name: true,
  profilePicture: true,
});

export const PostView = view<Post>()({
  author: UserView,
  content: true,
  id: true,
  title: true,
});

Now we can create a separate UserCard component that uses our UserView:

import { useView, ViewRef } from 'react-fate';

export const UserCard = ({ user: userRef }: { user: ViewRef<'User'> }) => {
  const user = useView(UserView, userRef);

  return (
    <div>
      <img src={user.profilePicture} alt={user.name} />
      <p>{user.name}</p>
    </div>
  );
};

And update PostCard to use our UserCard component:

import { UserCard } from './UserCard.tsx';

export const PostCard = ({ post: postRef }: { post: ViewRef<'Post'> }) => {
  const post = useView(PostView, postRef);

  return (
    <Card>
      <h2>{post.title}</h2>
      <UserCard user={post.author} />
      <p>{post.content}</p>
    </Card>
  );
};

View Spreads

When building complex UIs, you will often build multiple components that share the same data requirements. In fate, you can use view spreads to compose such views together. This is similar to GraphQL fragment spreads, but works with plain JavaScript objects.

Let's assume we want to fetch and display additional information about the author in the PostCard, such as their bio. Instead of directly assigning our UserView to the author field, we can instead spread it and add the bio field:

export const PostView = view<Post>()({
  author: {
    ...UserView,
    bio: true,
  },
  content: true,
  id: true,
  title: true,
});

Now the PostCard component can access the bio field of the author:

export const PostCard = ({ post: postRef }: { post: ViewRef<'Post'> }) => {
  const post = useView(PostView, postRef);

  return (
    <Card>
      <h2>{post.title}</h2>
      <UserCard author={post.author} />
      {/* Accessing the bio field */}
      <p>{post.author.bio}</p>
      <p>{post.content}</p>
    </Card>
  );
};

We can also spread multiple views together. For example, if we have another view called UserStatsView that selects some statistics about the user, we can include it in the PostView like this:

export const UserStatsView = view<User>()({
  followerCount: true,
  postCount: true,
});

export const PostView = view<Post>()({
  author: {
    ...UserView,
    ...UserStatsView,
    bio: true,
  },
  content: true,
  id: true,
  title: true,
});

Views are opaque objects. Even if you select the same field multiple times through different views, the composed object won't have conflicting fields or result in TypeScript errors. fate automatically deduplicates fields during runtime and ensures that each field is only fetched once.

useView and Suspense

We learned that useRequest is responsible for fetching data from the server and useView is used for reading data from the cache. In some situations data may not be available in the cache and useView might need to suspend the component to fetch only the missing data. Once that data is fetched and written to the cache, the component resumes rendering.

Tip: You can test this behavior in development mode with Fast Refresh (HMR) enabled in your bundler. When you edit the selection of a view, components using that view will suspend, fetch the missing data, and then resume rendering.

Type Safety and Data Masking

fate provides guarantees through TypeScript and during runtime that prevent you from accessing data that wasn't selected in a component. This ensures that you declare all the data dependencies at the right level in your component tree, and prevents accidental coupling between components.

In the below example, we forgot to select the content of a Post. As a result, type-checks fail and the content field is undefined during runtime:

const PostView = view<Post>()({
  id: true,
  title: true,
  // `content: true` is omitted.
});

const PostCard = ({ post: postRef }: { post: ViewRef<'Post'> }) => {
  const post = useView(PostView, postRef);

  return (
    <Card>
      <h2>{post.title}</h2>
      {/* TypeScript errors here, and `post.content` is undefined during runtime */}
      <p>{post.content}</p>
    </Card>
  );
};

Views can only be resolved against refs that include that view directly or via view spreads. If a component tries to resolve a view against a ref that isn't linked, it will throw an error during runtime:

const PostDetailView = view<Post>()({
  content: true,
});

const AnotherPostView = view<Post>()({
  content: true,
});

const PostView = view<Post>()({
  id: true,
  title: true,
  ...AnotherPostView,
});

const PostCard = ({ post: postRef }: { post: ViewRef<'Post'> }) => {
  const post = useView(PostView, postRef);
  return <PostDetail post={post} />;
};

const PostDetail = ({ post: postRef }: { post: ViewRef<'Post'> }) => {
  // This throws because the post reference passed into this component
  // is of type `AnotherPostView`, not `PostDetailView`.
  const post = useView(PostDetailView, postRef);
};

ViewRefs carry a set of view names they can resolve. useView throws if a ref does not include the required view.

Requests

Requesting Lists

The useRequest hook can be used to declare our data needs for a specific screen or component tree. At the root of our app, we can request a list of posts like this:

import { useRequest } from 'react-fate';
import { PostCard, PostView } from './PostCard.tsx';

export function App() {
  const { posts } = useRequest({ posts: { list: PostView } });
  return posts.map((post) => <PostCard key={post.id} post={post} />);
}

This component suspends or throws errors, which bubble up to the nearest error boundary. Wrap your component tree with ErrorBoundary and Suspense components to show error and loading states:

<ErrorBoundary FallbackComponent={ErrorComponent}>
  <Suspense fallback={<div>Loading…</div>}>
    <App />
  </Suspense>
</ErrorBoundary>

[!NOTE]

useRequest may issue multiple operations in the same render pass. fate transports can batch those operations into fewer network requests: the native HTTP transport batches same-microtask operations into one POST /fate request, and the tRPC adapter can use tRPC's HTTP Batch Link.

Requesting Objects by ID

If you want to fetch data for a single object instead of a list, you can specify the id and the associated view like this:

const { post } = useRequest({
  post: { id: '12', view: PostView },
});

If you want to fetch multiple objects by their IDs, you can use the ids field:

const { posts } = useRequest({
  posts: { ids: ['6', '7'], view: PostView },
});

Other Types of Requests

For any other queries, pass only the type and view:

const { viewer } = useRequest({
  viewer: { view: UserView },
});

Request Arguments

You can pass arguments to useRequest calls. This is useful for pagination, filtering, or sorting. For example, to fetch the first 10 posts, you can do the following:

const { posts } = useRequest({
  posts: {
    args: { first: 10 },
    list: PostView,
  },
});

Request arguments are part of the cache key. Two list requests for the same root with different filters or sorting arguments keep separate list state, and cursor arguments are merged into the same list when you load more pages. The selected view is part of the key as well: requesting PostCardView and PostDetailView can share normalized records, but fate still tracks whether the specific fields for each request are present.

Request Modes

useRequest supports different request modes to control caching and data freshness. The available modes are:

  • cache-first (default): Returns data from the cache if available, otherwise fetches from the network.
  • stale-while-revalidate: Returns data from the cache and simultaneously fetches fresh data from the network.
  • network-only: Always fetches data from the network, bypassing the cache.

You can pass the request mode as an option to useRequest:

const { posts } = useRequest(
  {
    posts: { list: PostView },
  },
  {
    mode: 'stale-while-revalidate',
  },
);

Cache Lifetime

fate stores records in a normalized cache keyed by __typename and id. Lists and root queries point at those records, and views read from the normalized cache. When a useRequest call is mounted, fate retains the request so the records and lists needed by that screen stay in memory. When the component unmounts, the request is released and fate schedules garbage collection.

Released requests are kept in a small release buffer before their data becomes collectible. This makes common route transitions cheap: navigating away from a screen and quickly coming back usually reuses the cached records instead of refetching them. The default release buffer stores the 10 most recently released requests.

You can tune the buffer when creating the client:

const fate = createClient({
  gcReleaseBufferSize: 20,
  roots,
  transport,
  types,
});

Set gcReleaseBufferSize to 0 in tests or very memory-sensitive environments when released screens should be collected immediately.

cache-first request handles are stable while their request is cached. If garbage collection later removes the data for a fulfilled request, the next cache-first request automatically fetches it again rather than returning stale references.

If you call fate.request(...) outside React and need the result to stay in memory across manual gc() calls, retain the same request for the lifetime of that work:

const request = { posts: { list: PostView } };
const retained = fate.retain(request);

try {
  const { posts } = await fate.request(request);
  // Use posts while this request is retained.
} finally {
  retained.dispose();
}

Garbage collection waits for active optimistic updates to settle before sweeping records. This keeps temporary optimistic records and their list positions stable while mutations are still pending.

SSR and Hydration

Create a request-scoped fate client on the server, preload the route data, and dehydrate its normalized cache:

const fate = createFateClient();
await fate.request({ post: { id: '12', view: PostView } });

return {
  fate: fate.dehydrate(),
};

Transport the returned value through your framework's loader serialization, React Server Component props, or a safely escaped JSON bootstrap script. The snapshot contains plain serializable values, so serializers such as Seroval can carry it without fate-specific integration. Treat the snapshot as opaque: hydrate it through fate rather than reading or editing its internal data.

On the browser, hydrate the new client before rendering components that call useRequest:

const fate = createFateClient();
fate.hydrate(loaderData.fate);

hydrateRoot(
  document,
  <FateClient client={fate}>
    <App />
  </FateClient>,
);

Hydrated cache-first requests resolve from the normalized cache without refetching. Hydration restores records, selected-field coverage, root queries, and list pagination state. It intentionally does not restore active requests, subscriptions, retainers, timers, or optimistic mutation state.

Snapshots carry a hydration scope and are rejected by clients with a different scope. Generated clients set a stable scope automatically. When constructing a client directly, pass hydrationScope and rotate it when deploying an incompatible cache schema or when separating cache namespaces:

const fate = createClient({
  hydrationScope: 'storefront-v2',
  // ...
});

Use hydrationLimits when an application needs stricter bootstrap payload limits. fate applies conservative defaults for total encoded values, collection sizes, and string lengths.

By default, hydration preserves values already present in the browser cache while adding missing server data. Pass { merge: 'replace' } only when the snapshot should authoritatively reset the durable cache:

fate.hydrate(loaderData.fate, { merge: 'replace' });

preserve-existing recursively combines plain scalar objects while keeping browser values on conflicts. Arrays, dates, entity references, and list windows are atomic: an existing browser value wins as a whole. Replaying a snapshot is safe and does not notify subscribers when durable cache state is unchanged.

Do not reuse request-scoped snapshots across users. Dehydrate after awaited route preloading: snapshots are point-in-time values and do not stream cache patches for data that resolves later. Hydration and dehydration reject clients with in-flight requests, so hydrate the initial snapshot before rendering.

Deferred Views

Use defer when a field should not block the parent view. The parent view receives a deferred handle immediately after the eager fields are available, and the component that reads that handle with useView, useListView, or useLiveListView decides which Suspense boundary handles the loading state.

import { Suspense } from 'react';
import { defer, useListView, useView, view, Deferred, ViewRef } from 'react-fate';

const CommentView = view<Comment>()({
  content: true,
  id: true,
});

const CommentConnectionView = {
  args: { first: 3 },
  items: { node: CommentView },
};

const PostView = view<Post>()({
  comments: defer(CommentConnectionView),
  content: true,
  id: true,
  title: true,
});

function PostCard({ post: postRef }: { post: ViewRef<'Post'> }) {
  const post = useView(PostView, postRef);

  return (
    <article>
      <h2>{post.title}</h2>
      <p>{post.content}</p>
      <Suspense fallback={<CommentsSkeleton />}>
        <PostComments comments={post.comments} />
      </Suspense>
    </article>
  );
}

function PostComments({
  comments,
}: {
  comments: Deferred<{ items: ReadonlyArray<{ node: ViewRef<'Comment'> }> }>;
}) {
  const [items, loadNext] = useListView(CommentConnectionView, comments);

  return (
    <section>
      {items.map(({ node }) => (
        <CommentCard comment={node} key={node.id} />
      ))}
      {loadNext ? <button onClick={loadNext}>Load more</button> : null}
    </section>
  );
}

Deferred fields are not optional data. They are explicit handles that existing view APIs can read. If the deferred selection is missing from the normalized cache, fate fetches only that missing selection and suspends the component that tried to resolve it.

This keeps parent components simple: eager fields like title and content are available when useView(PostView, postRef) returns, while slower or secondary fields such as comments can load under their own boundary.

GraphQL transports use the same client semantics today. The deferred field is omitted from the eager request and fetched when the deferred handle is resolved. GraphQL @defer is the natural transport representation for this feature, but consuming incremental multipart patches requires additional transport support before fate can safely normalize streamed patches from a single GraphQL response.

List Views

Pagination with useListView

You can wrap a list of references using useListView to enable connection-style lists with pagination support.

For example, you can define a CommentView and reuse it inside of a CommentConnectionView:

import { useListView, ViewRef } from 'react-fate';

const CommentView = view<Comment>()({
  content: true,
  id: true,
});

const CommentConnectionView = {
  args: { first: 10 },
  items: {
    node: CommentView,
  },
};

const PostView = view<Post>()({
  comments: CommentConnectionView,
});

Now you can apply the useListView hook inside of your PostCard component to read the list of comments and load more comments when needed:

export function PostCard({ detail, post: postRef }: { detail?: boolean; post: ViewRef<'Post'> }) {
  const post = useView(PostView, postRef);
  const [comments, loadNext] = useListView(CommentConnectionView, post.comments);

  return (
    <div>
      {comments.map(({ node }) => (
        <CommentCard comment={node} key={node.id} post={post} />
      ))}
      {loadNext ? (
        <Button onClick={loadNext} variant="ghost">
          Load more comments
        </Button>
      ) : null}
    </div>
  );
}

If loadNext is undefined, it means there are no more comments to load. If you want to instead load previous comments, you can use the third argument returned by useListView, which is loadPrevious. Similarly, if there are no previous comments to load, loadPrevious will be undefined.

Pagination Arguments

Connection views can define default arguments, and useListView carries those arguments forward when loading more pages:

const CommentConnectionView = {
  args: { first: 10 },
  items: {
    cursor: true,
    node: CommentView,
  },
  pagination: {
    hasNext: true,
    hasPrevious: true,
    nextCursor: true,
    previousCursor: true,
  },
};

When loadNext runs, fate sends the next cursor as after and keeps the page size in first. When loadPrevious runs, fate sends the previous cursor as before and uses last for the page size. This lets the server distinguish forward and backward pagination while keeping the component API small.

Additional arguments on a root request are scoped to that root list:

const { posts } = useRequest({
  posts: {
    args: { categoryId: category.id, first: 20 },
    list: PostConnectionView,
  },
});

The categoryId list above has its own cache entry and pagination state. Loading another page for that list does not update a different posts request with another category or search query.

Live Views

useLiveView resolves a ViewRef just like useView, but also keeps the selected object up to date through the native live SSE transport.

import { useLiveView, ViewRef } from 'react-fate';

export const PostCard = ({ post: postRef }: { post: ViewRef<'Post'> }) => {
  const post = useLiveView(PostView, postRef);

  return (
    <Card>
      <h2>{post.title}</h2>
      {/* Updates automatically! */}
      <p>{post.likes} likes</p>
    </Card>
  );
};

The API mirrors useView: pass a view and a ref, and get back the same masked data shape. A null ref returns null and does not subscribe.

How Live Updates Work

The native HTTP transport opens one Server-Sent Events (SSE) connection per fate client. When components mount or unmount live views, the client sends subscribe and unsubscribe control messages to the server. The server keeps those selections on the connection and sends updates only for records that connection subscribed to.

When the server sends an update, fate normalizes the selected record into the same cache used by requests, actions, and mutations. Components that read affected fields re-render automatically.

For example, if PostView selects likes, a live update that changes likes re-renders the PostCard. If another component only selected title, it does not re-render for a likes change.

Live deletion events remove the record from the normalized cache in the same way as mutations, and any lists or object fields that reference it are pruned.

Client Setup

Configure the native transport and point the client at your fate endpoint:

import { FateClient } from 'react-fate';
import { createFateClient } from 'react-fate/client';

export function App() {
  const fate = useMemo(
    () =>
      createFateClient({
        fetch: (input, init) =>
          fetch(input, {
            ...init,
            credentials: 'include',
          }),
        url: `${env('SERVER_URL')}/fate`,
      }),
    [],
  );

  return <FateClient client={fate}>{/* Components go here */}</FateClient>;
}

[!NOTE]

Live views use GET /fate/live for the single SSE stream and POST /fate/live for subscribe/unsubscribe control messages.

Server Setup

Live views use an event bus. By default, the bus signals that an object changed and fate refetches the selected object through the same data view pipeline used by byId queries before sending it to the client. Update events can also include changed field paths so fate only resolves the intersection of those paths and each active subscription.

Pass a live event bus to createFateServer and expose the native handler:

import { createFateServer, createHonoFateHandler, createLiveEventBus } from '@nkzw/fate/server';
import type { AppContext } from './context.ts';
import { sources } from './sources.ts';
import { Root } from './views.ts';

export const live = createLiveEventBus();

export const fate = createFateServer<AppContext>({
  live,
  roots: Root,
  sources,
});

app.all('/fate/*', createHonoFateHandler(fate));

fate keeps a bounded in-memory queue for each native SSE connection while live events are waiting to be resolved and sent. The default limit is 1000 queued events per connection. If a client falls behind and exceeds the limit, fate closes that live connection so server memory cannot grow without bound. You can tune the limit by passing the object form:

export const fate = createFateServer<AppContext>({
  live: {
    bus: live,
    maxQueueSize: 500,
  },
  roots: Root,
  sources,
});

Once this is in place, components can switch from useView to useLiveView without changing their view definitions or return types.

Live List Views

useLiveListView mirrors useListView, but subscribes to live connection events for the connection it receives:

import { useLiveListView, useLiveView, ViewRef } from 'react-fate';

export function PostCard({ post: postRef }: { post: ViewRef<'Post'> }) {
  const post = useLiveView(PostView, postRef);
  const [comments, loadNext] = useLiveListView(CommentConnectionView, post.comments);

  return (
    <>
      {comments.map(({ node }) => (
        <CommentCard comment={node} key={node.id} />
      ))}
      {loadNext ? <button onClick={loadNext}>Load more</button> : null}
    </>
  );
}

The hook returns the same tuple as useListView: items, loadNext, and loadPrevious. Live events append, prepend, insert, or delete edges from one connection without deleting the underlying records.

By default, live appends and prepends respect pagination boundaries. If the relevant edge still has more pages, fate keeps the incoming node attached to that edge instead of expanding the loaded window. For chat or activity streams where new items should keep appearing immediately, opt into visible live insertion on the connection view:

const MessageConnectionView = {
  args: { first: 30 },
  items: {
    node: MessageView,
  },
  live: {
    append: 'visible',
  },
};

Emit connection events on the server when list membership changes:

live.connection('Post.comments', { id: postId }).prependNode('Comment', comment.id);
live.connection('Post.comments', { id: postId }).deleteEdge('Comment', comment.id);

For root lists, use the generated root procedure name:

live.connection('posts', { categoryId }).prependNode('Post', post.id);

If the changed list cannot be described precisely, invalidate the active connection and fate will refetch it:

live.connection('posts', { categoryId }).invalidate();

Connection identity follows Relay's model: pagination args like first, last, after, and before are ignored for live connection matching, while filter args such as categoryId are part of the identity.

Emitting Events

After a mutation changes an object, emit an update event for that object:

export const postRouter = router({
  ...fate.procedures({
    view: postDataView,
  }),
  like: procedure.input(likeInput).mutation(async ({ ctx, input }) => {
    const post = await ctx.prisma.post.update({
      data: {
        likes: {
          increment: 1,
        },
      },
      where: { id: input.id },
    });

    live.update('Post', input.id);

    return post;
  }),
});

This tells fate that the Post changed. Every active live view for that post refreshes using the selection it subscribed with.

If you know which fields changed, pass them with changed to reduce the amount of data sent to each subscriber:

live.update('Post', input.id, { changed: ['likes'] });

With this version, a live view that selected likes refreshes only likes, while a live view that only selected unrelated fields is skipped entirely.

If a mutation changes a related object, emit for the object whose live view should refresh. For example, adding a comment usually changes the post's commentCount and comments list, so emit for the Post:

export const commentRouter = router({
  add: procedure.input(addCommentInput).mutation(async ({ ctx, input }) => {
    const comment = await ctx.prisma.comment.create({
      data: {
        content: input.content,
        postId: input.postId,
      },
    });

    live.update('Post', input.postId, { changed: ['commentCount', 'comments'] });

    return comment;
  }),
});

For deletions, emit a delete event for the deleted object if clients may be subscribed to it:

live.delete('Comment', input.id);

If deleting the object also changes another object, emit an update for that object too:

live.update('Post', postId, { changed: ['commentCount', 'comments'] });

You can pass an eventId when emitting. fate sends it on the native SSE event and includes the last received event ID when it resubscribes after a reconnect:

live.update('Post', input.id, {
  changed: ['likes'],
  eventId: `post:${input.id}:${Date.now()}`,
});

The default createLiveEventBus is an in-memory fanout bus and does not replay events that were emitted while a client was disconnected. Use a durable custom live bus if your deployment needs reconnects to catch up from lastEventId; otherwise the client receives future live events after it reconnects.

Error Handling

Live subscription errors are reported out of band. They do not replace the last cached data or throw through the component that called useLiveView.

Pass onLiveError when creating the client to send those failures to your logger or monitoring system:

const fate = createFateClient({
  fetch: (input, init) =>
    fetch(input, {
      ...init,
      credentials: 'include',
    }),
  onLiveError(error) {
    captureException(error);
  },
  url: `${env('SERVER_URL')}/fate`,
});

The handler runs in a microtask after the subscription reports the error. Components continue to read whatever data is currently available in the fate cache.

Actions

fate does not provide hooks for mutations like traditional data fetching libraries do. Instead, mutations are exposed in two ways:

  • fate.actions for use with useActionState and React Actions.
  • fate.mutations for traditional imperative mutation calls.

Server mutations are exposed automatically as actions and mutations by fate's Vite plugin. The transport determines where those mutations are declared:

  • With the native HTTP transport, mutations come from the mutations object passed to createFateServer.
  • With the tRPC adapter, mutations come from tRPC mutation procedures exposed through your fate-enabled router.
  • With Void, mutations use the same native fate server shape and are exposed through the Void route helpers.

If you have a mutation named post.like, a LikeButton component using fate Actions and an async component library could look like this:

import { useActionState } from 'react';
import { useFateClient } from 'react-fate';

const LikeButton = ({ post }: { post: { id: string; likes: number } }) => {
  const fate = useFateClient();
  const [result, like] = useActionState(fate.actions.post.like, null);

  return (
    <Button action={() => like({ input: { id: post.id } })}>
      {result?.error ? 'Oops!' : 'Like'}
    </Button>
  );
};

If you are not using an async component library, you can use React's useTransition to start the action in a transition:

const LikeButton = ({ post }: { post: { id: string; likes: number } }) => {
  const fate = useFateClient();
  const [, startTransition] = useTransition();
  const [result, like, isPending] = useActionState(fate.actions.post.like, null);

  return (
    <button
      disabled={isPending}
      onClick={() => {
        startTransition(() =>
          like({
            input: { id: post.id },
          }),
        );
      }}
    >
      {result?.error ? 'Oops!' : 'Like'}
    </button>
  );
};

By using useActionState, fate Actions integrate with Suspense and concurrent rendering.

Optimistic Updates

fate Actions support optimistic updates out of the box. For example, to update the post's like count optimistically, you can pass an optimistic object to the action call. This will immediately update the cache with the new like count and re-render all views that select the likes field:

like({
  input: { id: post.id },
  optimistic: { likes: post.likes + 1 },
});

When data changes through optimistic updates or otherwise, fate only re-renders the views that select the changed fields. In the above example, only views that select the likes field will re-render. If a view only selects the title field, it won't re-render when the likes field changes.

If a mutation fails, the cache will be rolled back to its previous state and any views depending on the mutated data will be updated.

Inserting New Objects

When a mutation inserts a new object, you can provide an optimistic object with a temporary ID to represent the new object in the cache until the server responds with the actual ID. For example, to add a new comment to a post optimistically, you can do the following:

const content = 'New Comment text';
addComment({
  input: { content, postId: post.id },
  optimistic: {
    author: { id: user.id, name: user.name },
    content,
    id: `optimistic:${Date.now().toString(36)}`,
    post: { commentCount: post.commentCount + 1, id: post.id },
  },
});

By default, fate inserts new records after existing items in matching root lists and nested lists. For a newest-first list, pass insert: 'before' so optimistic records appear at the beginning:

addComment({
  input: { content, postId: post.id },
  insert: 'before',
  optimistic: {
    content,
    id: `optimistic:${Date.now().toString(36)}`,
    post: { id: post.id },
  },
});

Insertion respects pagination boundaries. If you append to a list that still has a next page, fate keeps the new record attached to the unresolved trailing edge instead of mixing it into the loaded page. As you load more pages, the inserted record stays at the end until the server returns the canonical item or the list reaches the edge. The same behavior applies to prepends while hasPrevious is true.

Multiple pending optimistic inserts keep their visible order. For example, two insert: 'before' calls on a newest-first feed show the second optimistic item before the first, matching what users expect from newly created content.

Selecting a View with Actions

Mutations may change data that is not directly specified in the mutation result. For example, adding a comment increases the post's comment count. For such cases, you can provide a view to an action that specifies which fields to fetch as part of the mutation:

addComment({
  input: { content: 'New Comment text', postId: post.id },
  view: view<Comment>()({
    ...CommentView,
    post: { commentCount: true },
  }),
});

The server will return the selected fields and fate updates the cache and re-renders all views that depend on the changed data. The action result contains the newly added comment with the selected fields:

const [result, addComment] = useActionState(fate.actions.comment.add, null);

const newComment = result?.result;
if (newComment) {
  // All the fields selected in the view are available on `newComment`:
  console.log(newComment.post.commentCount);
}

Mutations

fate Actions are the recommended way to execute server mutations in React components. However, there are cases where you might want to call mutations imperatively, outside of React components, or without waiting for previous actions to finish like useActionState does. For such cases, you can use fate.mutations to call mutations imperatively:

const result = await fate.mutations.comment.add({
  input: { content, postId: post.id },
});

You can call mutations from anywhere, and without waiting for previous mutations to finish. The mutation API matches the API of fate Actions, including optimistic updates and view selection. With mutations, you'll need to handle loading states and errors manually, and the result is returned as a promise.

Mutation Server Implementation

fate Actions & Mutations are backed by regular server mutations. If you already know how your fate server is wired, the client-side API above is the same regardless of transport. If not, start with the server setup for your environment:

  • Native HTTP custom mutations use createFateServer({ mutations }).
  • tRPC fate setup wires fate into your tRPC router; custom writes can use the same fate.createPlan and fate.resolveById helpers shown there.
  • Void integration exposes a native fate server from Void routes; define mutations with the native createFateServer({ mutations }) API and serve them through defineVoidFateRoute.

Here is a native HTTP mutation for post.like:

export const fate = createFateServer({
  mutations: {
    'post.like': {
      input: likeInput,
      resolve: async ({ ctx, input, select }) => {
        await ctx.prisma.post.update({
          data: {
            likes: {
              increment: 1,
            },
          },
          where: { id: input.id },
        });

        return sources.resolveById({
          ctx,
          id: input.id,
          input: { select },
          view: postDataView,
        });
      },
      type: 'Post',
    },
  },
  roots: Root,
  sources,
});

The equivalent tRPC mutation lives in your router and returns the selected shape that the client asked for:

import { z } from 'zod';
import { connectionArgs, createResolver } from '@nkzw/fate/server';
import { procedure, router } from '../init.ts';
import { postDataView, PostItem } from '../views.ts';

export const postRouter = router({
  like: procedure
    .input(
      z.object({
        args: connectionArgs,
        id: z.string().min(1, 'Post id is required.'),
        select: z.array(z.string()),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      const { resolve, select } = createResolver({
        ...input,
        ctx,
        view: postDataView,
      });

      return resolve(
        await ctx.prisma.post.update({
          data: {
            likes: {
              increment: 1,
            },
          },
          select,
          where: { id: input.id },
        } as PostUpdateArgs),
      );
    }),
});

See Server Integration for complete native HTTP and tRPC setup examples, and Void Integration for route helpers when your app runs on Void.

Action & Mutation Error Handling

fate Actions & Mutations separate error handling into two scopes: "call site" and "boundary". Call site errors are expected to be handled at the location where the action or mutation is called. Boundary errors are unexpected errors that should be handled by a higher-level error boundary.

If your server returns a NOT_FOUND error with code 404, the result of an Action or Mutation will contain an error object that you can handle at the call site:

const [result] = useActionState(fate.actions.post.delete, null);

if (result?.error) {
  if (result.error.code === 'NOT_FOUND') {
    // Handle not found error at call site.
  } else {
    // Handle other *expected* errors.
  }
}

However, if an INTERNAL_SERVER_ERROR error with code 500 occurs, it will be thrown and can be caught by the nearest React error boundary:

<ErrorBoundary FallbackComponent={ErrorComponent}>
  <Suspense fallback={<div>Loading…</div>}>
    <PostPage postId={postId} />
  </Suspense>
</ErrorBoundary>

You can find the error classification behavior in mutation.ts.

Deleting Records

When you want to delete a record using fate Actions, you can pass a delete: true flag to the action call. This flag removes the object from the cache and re-renders all views that depend on the deleted data:

const [result, deleteAction] = useActionState(fate.actions.post.delete, null);

deleteAction({
  input: { id: post.id },
  delete: true,
});

Resetting Action State

When using useActionState, the result of the action is cached until the component using the action is unmounted. When a mutation fails with an error, you might want to clear the error state without invoking the action again. fate Actions take a 'reset' token to reset the action state:

const [result, like] = useActionState(fate.actions.post.like, null);

useEffect(() => {
  if (result?.error) {
    // Reset the action state after 3 seconds.
    const timeout = setTimeout(() => startTransition(() => like('reset')), 3000);
    return () => clearTimeout(timeout);
  }
}, [like, result]);

Controlling List Insertion Behavior

When inserting new objects into lists, the default behavior is to append the new object to the list. You can provide an insert option with before, after or none values to customize this behavior and specify where the new object should be inserted in the list:

addComment({
  input: { content: 'New Comment text', postId: post.id },
  insert: 'before', // Insert the new comment at the beginning of the list.
});

Or, use the none option if you want to ignore inserting the new object into any lists:

addComment({
  input: { content: 'New Comment text', postId: post.id },
  insert: 'none', // Do not insert the new comment into any lists.
});

Persistence

fate can optionally keep data available across page reloads and save mutations while a user is offline. When the user comes back, their views can show previously loaded data and their pending changes continue where they left off.

Persistence builds on fate's normalized cache, Requests, and Actions. You configure storage only once, without changing how you use fate.

Client Setup

The persistence layer is part of @nkzw/fate, with storage adapters installed separately. For a browser app using IndexedDB, add the adapter:

vp add @nkzw/fate-indexeddb

Then pass persistence when creating the client:

import { createPersistence } from '@nkzw/fate/persistence';
import { createIndexedDBStorage } from '@nkzw/fate-indexeddb';
import { createFateClient } from 'react-fate/client';

const fate = createFateClient({
  persistence: createPersistence({
    key: `workspace:${workspaceId}:user:${userId}`,
    storage: createIndexedDBStorage(),
  }),
  url: '/api/fate',
});

By default, fate keeps loaded data for one day, with a storage budget of 25 MiB. You can change both values:

persistence: createPersistence({
  key: `workspace:${workspaceId}:user:${userId}`,
  maxAge: 24 * 60 * 60 * 1000,
  maxBytes: 25 * 1024 * 1024,
  storage: createIndexedDBStorage(),
}),

Create the browser client after you know which user is signed in. The key separates saved data and mutations by account and workspace, and must match the authenticated scope in the server setup. When switching accounts, dispose the previous persistence session and create a new client with the new account's key.

[!NOTE]

Persistence saves your app's data. To load the app itself while offline, you'll also need a service worker that makes its HTML, JavaScript, and other assets available. fate does not install a service worker or download pages the user hasn't visited.

Cache Lifetime

You can keep the data for a specific screen longer by passing persist to useRequest. For example, to keep a list of posts for three days:

const { posts } = useRequest(
  {
    posts: { list: PostView },
  },
  {
    persist: { maxAge: 3 * 24 * 60 * 60 * 1000 },
  },
);

The same option works with fate.request(...) and Vue's useRequest. If a screen uses several requests, set the option on each request whose data you want to keep longer.

fate stores objects by their type and ID, just like the in-memory cache. If a post appears in both your feed and a detail screen, both requests share the same saved post. Each request describes which fields and related objects it needs, including list membership and pagination state.

For example, your feed might keep posts for one day, while the detail screen keeps them for three days. After one day, the fields needed by the detail screen remain available. Fields selected only by the feed can be removed. You don't need to coordinate separate copies of the same post or manually patch each request's cache.

maxAge is measured in milliseconds from when the data was fetched successfully. Reading saved data or rendering the screen again does not restart that lifetime. If a request fetches one missing post, it only renews the data it fetched. Other posts already in the cache keep their original age. Changing a cached request's maxAge also uses the original fetch time.

When callers share a pending request, the latest explicit persist.maxAge also applies to that request's eventual cache write.

Pass persist: { maxAge: 0 } to skip saving data for a request. Shared objects may still be saved for other requests, so this option does not delete all copies of an object.

The in-memory garbage collector continues to work independently. A post can be removed from memory while its saved copy remains available for a later visit. On startup, fate restores pending mutations, then loads saved data as requests need it. It does not load the entire saved cache into memory.

Refreshing Data

Keeping data for three days doesn't mean waiting three days for updates. You can use the existing request modes to choose when to fetch fresh data:

  • cache-first (default): Uses available saved data and fetches missing data from the network.
  • stale-while-revalidate: Shows saved data and refreshes it in the background. If the refresh fails, the saved data stays visible.
  • network-only: Requires a network response, even if saved data is available.

For example, to show the previous session's posts immediately and update them on reload:

const { posts } = useRequest(
  {
    posts: { list: PostView },
  },
  {
    mode: 'stale-while-revalidate',
    persist: { maxAge: 3 * 24 * 60 * 60 * 1000 },
  },
);

Expiration controls how long data stays in storage. It does not remove data from a mounted view or change the in-memory fetch policy. For ongoing server updates, use Live Views.

Cache Size

When saved data reaches maxBytes, fate removes expired data first, then releases the least recently used requests until the new data fits. Objects still needed by another saved request remain available, and shared objects count toward the budget only once. A response that is too large to save can still be used in memory without removing other saved requests to make room for it.

The budget includes encoded data, keys, cache metadata, and the saved mutation queue. Your storage backend may use additional space for its own bookkeeping. maxBytes controls saved data; the existing garbage collector controls the lifetime of data in memory.

fate batches cache writes and yields during large traversals and writes so other work on the page can continue. The mutation journal stores each entry separately and writes only changed entries, so confirming a mutation does not rewrite the entire queue. Changes to scalar fields write the affected record, while changes to relationships also update the saved data that depends on them.

Pending mutations are never removed to make room for cached data. If a new mutation cannot fit, it fails before fate applies its optimistic update or sends it to the server.

[!NOTE]

Already accepted mutations must still be able to finish. Their recovery data and saved results can exceed the budget if they grow or you lower maxBytes. In that case, fate releases the read cache and rejects new durable mutations until capacity is available. Local confirmation receipts count toward the budget until their cache changes have been saved. fate then removes them automatically, making room for new mutations.

Actions & Mutations

With persistence configured, fate saves actions and mutations locally before applying their optimistic updates or sending them to the server. The API is the same as for regular Actions:

const [result, like] = useActionState(fate.actions.post.like, null);

like({
  input: { id: post.id },
  optimistic: { likes: post.likes + 1 },
});

If the user likes a post while offline, the like count updates immediately. Reloading the page restores the pending action and its optimistic update. When the connection returns and a client is running, fate sends the action to the server and updates the post with the confirmed result.

Mutations from one client are saved in invocation order and sent in the order they were saved, one at a time for each persistence key. Tabs sharing that key coordinate delivery. Temporary network and server failures are retried with increasing delays, up to 30 seconds between attempts. Authentication failures stay pending so delivery can resume after the user signs in again. A terminal client error rolls back the optimistic update and follows fate's existing error handling.

The mutation promise resolves after remote confirmation has been saved locally. It can remain pending while offline. Closing the page loses the JavaScript promise, but the saved mutation and optimistic update remain. After a reload, use the persistence state to show pending and failed changes.

Skipping Persistence

For a call that should run immediately without being saved or retried, pass persist: false:

await fate.mutations.analytics.record({
  input: { event: 'opened-settings' },
  persist: false,
});

The same option works with fate.actions. A successful result can still update the normal cache. Without persistence configured, actions and mutations keep their existing behavior.

Creating Objects Offline

Use a stable, client-generated ID when creating an object offline. For example, a new comment and a later edit to that comment can use the same ID, allowing fate to send the creation before the edit when the user reconnects.

If your server assigns IDs, wait for the creation result before constructing a dependent mutation. fate does not rewrite arbitrary foreign keys inside saved inputs. A failed creation also does not automatically cancel later mutations; your server should validate them as usual.

Mutation inputs and optimistic updates must be serializable with fate's hydration codec. Functions, streams, and File objects cannot be queued. For uploads, save the content first and queue a reference to it, or use persist: false for the upload itself.

Server Deduplication

A connection can fail after the server has already applied a mutation. For example, the server might increment a post's like count, but the response never reaches the browser. Retrying that mutation without server support would increment the count twice.

fate assigns an identity to each saved mutation and reuses it on every attempt. The server records the result alongside the mutation's database changes, in the same transaction. When the same mutation arrives again, the server returns the saved result.

For the native HTTP transport, configure createMutationIdempotency on your server. The following example uses application-provided helpers to lock a mutation identity and read or insert its receipt:

import { createMutationIdempotency } from '@nkzw/fate/persistence/server';
import { createFateServer } from '@nkzw/fate/server';

const server = createFateServer({
  // ...roots, sources, mutations, context...
  idempotency: createMutationIdempotency({
    scope: (ctx) => `workspace:${ctx.workspace.id}:user:${ctx.user.id}`,
    store: {
      transaction: (ctx, scope, id, run) =>
        database.transaction(async (tx) => {
          await lockMutationIdentity(tx, scope, id);
          return run({
            context: { ...ctx, db: tx },
            read: () => readReceipt(tx, scope, id),
            write: (receipt) => insertReceipt(tx, scope, id, receipt),
          });
        }),
    },
  }),
});

Your app supplies database, lockMutationIdentity, readReceipt, and insertReceipt. The lock must serialize attempts with the same (scope, id) across server processes, including the first attempt before a receipt exists. Mutation resolvers must use the transaction's ctx.db, so their changes and the receipt commit together. A unique index on the receipt table alone cannot protect changes made outside that transaction.

See example/persistence/server.ts for a complete SQLite implementation, including the receipt table and transaction handling.

The helper checks the identity against the authenticated scope and rejects reuse with different mutation names, inputs, or selections. Server receipts do not expire: a user might reconnect much later with a mutation whose response was lost. Keep receipts for as long as an old mutation could still arrive.

A database transaction cannot roll back an email, payment, or webhook sent to another service. For those effects, use a transactional outbox and the destination's idempotency support. The transaction integration guarantees one committed database effect; network requests and resolver attempts can still happen more than once.

Native HTTP sends durable mutations and receipt-only recovery using protocol version 2, so older servers reject unsupported requests before executing them. Ordinary requests and live subscriptions continue to use version 1. A current server without the idempotency integration also rejects durable mutations before running their resolvers.

tRPC, GraphQL, and Custom Transports

For tRPC, GraphQL, or a custom transport, provide a mutateDurably(name, input, select, identity) method that sends the identity to an endpoint with server deduplication. Regular calls continue to use mutate(name, input, select).

Both createTRPCTransport and createGraphQLTransport, including their generated clients, accept mutateDurably. For example, you can use a native fate endpoint for durable mutations alongside your existing transport:

const durableHTTP = createHTTPTransport<MyAPI>({
  url: '/api/fate',
  // Use the same authenticated headers as your other transport.
});

const fate = createFateClient({
  // ...your generated tRPC or GraphQL client options...
  persistence: createPersistence({ key: accountKey, storage: createIndexedDBStorage() }),
  mutateDurably: durableHTTP.mutateDurably,
});

Both endpoints need to agree on mutation names, inputs, results, and entity IDs. A custom GraphQL adapter should unwrap its response and decode GraphQL global IDs before returning data to fate.

You can also use the same idempotency helper inside an existing tRPC or GraphQL resolver. Validate the input and identity at the endpoint, then pass them to execute:

return idempotency.execute({
  ctx,
  identity: input.identity,
  input: input.update,
  name: 'post.update',
  select: input.select,
  resolve: (transactionContext) => updatePost(transactionContext, input.update),
});

The adapter must pass the entire identity on every attempt, including replayOnly when present. With replayOnly: true, the endpoint must return the existing receipt or a 404 if none exists, without executing the mutation. createMutationIdempotency handles both delivery and receipt-only recovery. Adding an identity to a header that the server ignores does not prevent duplicate effects.

If a client has registered mutations but no durable adapter, the persistence session reports a configuration error. Saved reads and persist: false calls still work. New durable calls fail before being queued, and existing queued mutations sta