# Next.js (https://effetch-query.pages.dev/docs/frameworks/nextjs)

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](https://effetch-query.pages.dev/docs/frameworks), and the round trip itself is in
[Send the cache](https://effetch-query.pages.dev/docs/server-rendering). The examples import `api.ts`
and `todos.ts` from [Getting started](https://effetch-query.pages.dev/docs/getting-started), and
`todo-list.tsx` from [Send the cache](https://effetch-query.pages.dev/docs/server-rendering).

## 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](https://effetch-query.pages.dev/docs/frameworks/nextjs#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:

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

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

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

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

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

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:

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

export { TodoList } 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`:

```tsx
import { QueryClient } from "@monarcode/effetch-query";
import { HydrationBoundary } from "@monarcode/effetch-query/react";

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

export default async function TodosPage() {
  const client = getQueryClient();
  await client.prefetch(todos());
  return (
    <HydrationBoundary
      state={QueryClient.dehydrate(client, { pending: "promise" })}
    >
      <TodoList />
    </HydrationBoundary>
  );
}
```

## 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:

```tsx
"use client";

import * as ManagedRuntime from "effect/ManagedRuntime";

import { QueryClient } from "@monarcode/effetch-query";
import { QueryProvider } from "@monarcode/effetch-query/react";
import { type ReactNode, useState } from "react";

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

const appRuntime = ManagedRuntime.make(ApiClientLive);
let browserClient: QueryClient.QueryClient | undefined;

const makeClient = () =>
  QueryClient.make({
    runtime: appRuntime,
    queries: { defaults: { staleTime: "30 seconds" } },
  });

const getClient = () =>
  typeof window === "undefined"
    ? makeClient()
    : (browserClient ??= makeClient());

// The root layout renders its children inside it.
export function Providers({ children }: { readonly children: ReactNode }) {
  const [client] = useState(getClient);
  return <QueryProvider client={client}>{children}</QueryProvider>;
}
```

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:

```tsx
import { QueryClient } from "@monarcode/effetch-query";
import { HydrationBoundary } from "@monarcode/effetch-query/react";

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

export default function TodosPage() {
  const client = getQueryClient();
  void client.prefetch(todos());
  return (
    <HydrationBoundary
      state={QueryClient.dehydrate(client, { pending: "promise" })}
    >
      <TodoList />
    </HydrationBoundary>
  );
}
```

## 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:

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

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

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

const User = Schema.Struct({ name: Schema.String });

export const account = Query.make({
  key: ["account"],
  run: ApiClient.use((client) => client.get("/me", { output: User })).pipe(
    Effect.catchTag("HttpError", (error) =>
      error.status === 401
        ? Effect.sync(() => redirect("/login"))
        : Effect.fail(error),
    ),
  ),
  schema: { success: User },
});
```

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](https://effetch-query.pages.dev/docs/server-rendering): 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

- [Stream the cache](https://effetch-query.pages.dev/docs/server-rendering/streaming): what happens to a
  query still loading when the page is sent.
- [What's sent](https://effetch-query.pages.dev/docs/server-rendering/whats-sent): schemas that
  transform, keys and failures.
- [Sign out and switch accounts](https://effetch-query.pages.dev/docs/cache/accounts): keep one user's
  cached data away from the next.