Skip to Content
Effetch Query
Frameworks

Next.js

Use Effetch Query in the Next.js App Router.

Your app uses the Next.js App Router. Server components load the data, and client components read it, each from a client of their own. The App Router needs no integration package: the core and ./react cover it.

This page shows the App Router's wiring. The rules every framework shares, a staleTime, streaming and redirects, are in Frameworks, and the round trip itself is in Send the cache. The examples import api.ts and todos.ts from Getting started, and todo-list.tsx from Send the cache.

Before you begin

You need:

  • React 19;
  • Next.js 15.1 or later, where after from next/server is stable;
  • the App Router. For the Pages Router, see The Pages Router.

1. Make a client per request for server components

React's cache() gives every server component of a request the same client, and Next.js's after() disposes it after the response is sent:

query-client.ts
import * as  from "effect/ManagedRuntime";

import {  } from "@monarcode/effetch-query";
import {  } from "next/server";
import {  } from "react";

import {  } from "./api.js";

// Builds your services once, for every request's client to share.
const  = .();

// Every server component of a request gets the same client. It's disposed
// after the response is sent, streamed results included.
export const  = (() => {
  const  = .({ :  });
  (() => .());
  return ;
});

Call getQueryClient from server components only: React's cache() memoizes only while it renders them. import "server-only" at the top of the file makes importing it from a client component a build error.

2. Mark the components that read queries

TodoList reads a query, so it's a client component. Mark it with "use client", in a file of its own:

todo-list-view.tsx
"use client";

export {  } from "./todo-list.js";

Keep the queries themselves out of "use client" files, in a file such as todos.ts. A server component that imports from a "use client" file gets references to its exports, not the queries.

3. Prefetch in the page

The page, a server component, prefetches the todos and passes their state to TodoList under a HydrationBoundary:

import {  } from "@monarcode/effetch-query";
import {  } from "@monarcode/effetch-query/react";

import {  } from "./query-client.js";
import {  } from "./todo-list-view.js";
import {  } from "./todos.js";

export default async function () {
  const  = ();
  await .(());
  return (
    <
      ={.(, { : "promise" })}
    >
      < />
    </>
  );
}

4. Give the client components a client

Client components get their own client from a QueryProvider in the root layout. The browser keeps one for the page's lifetime, with a staleTime. On the server, Next.js renders client components for every request, so each render gets its own:

"use client";

import * as  from "effect/ManagedRuntime";

import {  } from "@monarcode/effetch-query";
import {  } from "@monarcode/effetch-query/react";
import { type ,  } from "react";

import {  } from "./api.js";

const  = .();
let : . | undefined;

const  = () =>
  .({
    : ,
    : { : { : "30 seconds" } },
  });

const  = () =>
  typeof  === "undefined"
    ? ()
    : ( ??= ());

// The root layout renders its children inside it.
export function ({  }: { readonly :  }) {
  const [] = ();
  return < ={}>{}</>;
}

A server render's client isn't disposed: nothing says when React is done with it, so it's kept until its queries' gcTime passes. Making it from a runtime means it never builds services of its own.

On client navigation, the page's state comes with its payload, and the boundary loads what's newer than the browser's cache.

Stream a query

To send the page before the todos have loaded, start the prefetch without awaiting it. The state goes to the browser as promises, which Next.js streams, and TodoList shows the todos when they land:

import {  } from "@monarcode/effetch-query";
import {  } from "@monarcode/effetch-query/react";

import {  } from "./query-client.js";
import {  } from "./todo-list-view.js";
import {  } from "./todos.js";

export default function () {
  const  = ();
  void .(());
  return (
    <
      ={.(, { : "promise" })}
    >
      < />
    </>
  );
}

Redirect from a query

Call Next.js's redirect() and notFound() from the run of a query that server components load. Both throw, so call them inside the Effect, where a throw is a defect:

import * as  from "effect/Effect";
import * as  from "effect/Schema";
import {  } from "next/navigation";

import {  } from "@monarcode/effetch-query";

import {  } from "./api.js";

const  = .({ : . });

export const  = .({
  : ["account"],
  : .(() => .("/me", { :  })).(
    .("HttpError", () =>
      . === 401
        ? .(() => ("/login"))
        : .(),
    ),
  ),
  : { :  },
});

Load it in the page with await getQueryClient().fetch(account). client.fetch rejects with what redirect() threw, and Next.js follows it. client.prefetch never rejects, so it doesn't redirect. In a client component, the failure is a QueryFailure, which Next.js doesn't treat as a redirect or a not-found.

The Pages Router

The Pages Router has no server components, so it's the recipe in Send the cache: make a client per request in getServerSideProps, prefetch, dehydrate, dispose it, and return the state as a prop for a HydrationBoundary. Props are JSON, so don't pass pending: "promise".

What's next

On this page