# Next.js (https://session-kit.pages.dev/docs/setups/next)

Your Next.js app uses the App Router, and you want the first response to show
the signed-in page, with no "Checking session…" state and no flash of
signed-out content. To do that, the server has to hold the session. In this
guide, you keep it in an encrypted cookie: a Server Function signs in, Proxy
refreshes the tokens, and Server Components read the session.

Client Components get a small client that mirrors the session the server
rendered, and the [hooks](https://session-kit.pages.dev/docs/getting-started#4-read-the-session-in-react)
work with it. [Server rendering](https://session-kit.pages.dev/docs/server-rendering) explains how the
pieces fit. A complete app is in
[`examples/next-app`](https://github.com/monarcode/session-kit/tree/main/examples/next-app).

## Before you begin

- Next.js 16 with the App Router, which needs Node.js 20.9 or newer. See
  [Compatibility](https://session-kit.pages.dev/docs/reference/compatibility) for the other versions.
- A secret of 32 or more random characters to seal the cookie, such as the
  output of `openssl rand -base64 32`, set as `SESSION_SECRET` on the server.
  `next build` doesn't need it.
  [The secret](https://session-kit.pages.dev/docs/server-rendering/server-sessions#the-secret) says how to
  keep and rotate it.
- The code signs in with [DummyJSON](https://dummyjson.com/docs/auth)'s test
  backend, as [Getting started](https://session-kit.pages.dev/docs/getting-started) does. Replace its URLs
  with your backend's.

## Installation

To install the packages, run the following command:

```npm
npm install @monarcode/session-kit next zod
```

## 1. Create the server engine

The server engine keeps the session in a cookie sealed with your secret, and
refreshes the tokens with your backend. `createServerAuth` from
`@monarcode/session-kit/server` makes it. Create it in a server-only module,
so Next refuses to bundle it for the browser:

```ts title="lib/auth/server.ts"
import "server-only";
import { createServerAuth } from "@monarcode/session-kit/server";
import { z } from "zod";

export const API = "https://dummyjson.com";

const userSchema = z.object({ id: z.number(), firstName: z.string() });
const tokens = z.object({ accessToken: z.string(), refreshToken: z.string() });

export const serverAuth = createServerAuth({
  name: "app",
  user: userSchema,
  secret: process.env.SESSION_SECRET!,
  refresh: async ({ refreshToken, signal }) => {
    const response = await fetch(`${API}/auth/refresh`, {
      method: "POST",
      signal,
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ refreshToken }),
    });
    // DummyJSON rejected the refresh token: sign out.
    if (response.status === 401 || response.status === 403) return null;
    if (!response.ok) throw new Error(`Refresh failed (${response.status})`);
    return tokens.parse(await response.json());
  },
});

/** Signs in with your backend, from the server. */
export async function login(username: string, password: string) {
  const response = await fetch(`${API}/auth/login`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ username, password }),
  });
  const body: unknown = await response.json().catch(() => null);
  if (!response.ok) {
    // The backend says why, such as wrong credentials, in `message`.
    const failure = z.object({ message: z.string() }).safeParse(body);
    throw new Error(
      failure.success
        ? failure.data.message
        : `Sign-in failed (${response.status})`,
    );
  }
  return { ...tokens.parse(body), user: userSchema.parse(body) };
}
```

`server-only` comes with Next, so there's nothing to install for it. [Server
sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions) covers the engine's other
options, the cookie, and signing out.

## 2. Read the session in Server Components

`nextSession` from `@monarcode/session-kit/next` gives your app its session
over Next's cookies. Session kit doesn't import `next`, so pass it Next's own
`cookies` and `redirect`. Create it in a server-only module too:

```ts title="lib/auth/session.ts"
import "server-only";
import { nextSession } from "@monarcode/session-kit/next";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";

import { serverAuth } from "./server";

export const session = nextSession(serverAuth, { cookies, redirect });
```

In a Server Component, `await session.get()` resolves `{ sessionId, user }`
or `null`. It holds no tokens, so it's safe to pass to Client Components. It
doesn't set cookies, as Server Components can't, so Proxy refreshes first,
in the next step.

## 3. Refresh in Proxy

Proxy refreshes tokens that are about to expire before any page or Server
Function reads them. `session.refresh(request, response)` sets the new cookie
on the response, and Next passes it on to the Server Components that render
the same request:

```ts title="proxy.ts"
import { NextResponse, type NextRequest } from "next/server";

import { session } from "./lib/auth/session";

export function proxy(request: NextRequest) {
  return session.refresh(request, NextResponse.next());
}

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
};
```

Here's what to know about the refresh:

- It refreshes tokens that expire within 60 seconds. For tokens that live a
  minute or less, pass a smaller `within` to `nextSession`, such as
  `nextSession(serverAuth, { cookies, redirect, within: 15 })`.
- If the refresh fails, the page still renders with the cookie as it is.
- Server Functions are `POST` requests to the page that calls them, so keep
  the matcher wide enough to include those pages.

[Requests that can't set cookies](https://session-kit.pages.dev/docs/server-rendering/server-sessions#requests-that-cant-set-cookies)
explains why the refresh happens there.

## 4. Add the session route and the sign-in action

The browser's client reads the session and signs out through a session
route: a Route Handler in your app that the browser's client calls.
`sessionRoute` from `@monarcode/session-kit/next` makes its `GET` and `POST`
handlers. Pass it Next's `cookies`:

```ts title="app/api/session/route.ts"
import { sessionRoute } from "@monarcode/session-kit/next";
import { cookies } from "next/headers";

import { serverAuth } from "../../../lib/auth/server";

export const { GET, POST } = sessionRoute(serverAuth, { cookies });
```

The session route answers your own site's pages only, so another site can't
sign the user out: see [The session route](https://session-kit.pages.dev/docs/security#the-session-route).

Signing in is yours, as it takes your form's input. A Server Function signs
in with your backend and sets the cookie with `session.signIn`:

```ts title="app/actions.ts"
"use server";

import { z } from "zod";

import { login } from "../lib/auth/server";
import { session } from "../lib/auth/session";

const credentials = z.object({ username: z.string(), password: z.string() });

export async function signInAction(input: unknown) {
  const { username, password } = credentials.parse(input);
  try {
    const tokens = await login(username, password);
    return { session: await session.signIn(tokens) };
  } catch (error) {
    return {
      error: error instanceof Error ? error.message : "Sign-in failed",
    };
  }
}
```

`signInAction` returns its failure rather than throwing it, as Next advises
for expected errors. In production, Next hides a thrown error's message from
the browser.

## 5. Create the browser client

`createMirrorAuth` makes the client that Client Components use, from the
session the layout read, the session route and your sign-in action:

```ts title="lib/auth/client.ts"
import { createMirrorAuth, type SessionOf } from "@monarcode/session-kit";

import { signInAction } from "../../app/actions";
// Types only: left out of the browser's bundle.
import type { serverAuth } from "./server";

export type AppSession = SessionOf<typeof serverAuth>;

export function createAppAuth(session: AppSession | null) {
  return createMirrorAuth({
    name: "app",
    session,
    endpoint: "/api/session",
    signIn: async (input: { username: string; password: string }) => {
      const result = await signInAction(input);
      if ("error" in result) throw new Error(result.error);
      return result.session;
    },
  });
}

export type AppAuth = ReturnType<typeof createAppAuth>;
```

`useMirrorAuth` from `@monarcode/session-kit/react` creates the client in a
Client Component, once per request on the server, never at module level. It
keeps the client and the server in step both ways. When the session changes
in the browser, it calls `onChange`, here `router.refresh()`, which renders
the Server Components again. Register the client's type where you render
`AuthProvider`, so the hooks carry your user:

```tsx title="app/providers.tsx"
"use client";

import type { ReactNode } from "react";

import { AuthProvider, useMirrorAuth } from "@monarcode/session-kit/react";
import { useRouter } from "next/navigation";

import {
  createAppAuth,
  type AppAuth,
  type AppSession,
} from "../lib/auth/client";

// Types `AuthProvider` and the hooks with this client.
declare module "@monarcode/session-kit" {
  interface Register {
    auth: AppAuth;
  }
}

export function Providers(props: {
  session: AppSession | null;
  children: ReactNode;
}) {
  const router = useRouter();
  const auth = useMirrorAuth({
    create: createAppAuth,
    session: props.session,
    onChange: () => router.refresh(),
  });
  return <AuthProvider client={auth}>{props.children}</AuthProvider>;
}
```

Render the providers in the root layout, with the session it reads:

```tsx title="app/layout.tsx"
import type { ReactNode } from "react";

import { session } from "../lib/auth/session";
import { Providers } from "./providers";

export default async function RootLayout(props: { children: ReactNode }) {
  const current = await session.get();
  return (
    <html lang="en">
      <body>
        <Providers session={current}>{props.children}</Providers>
      </body>
    </html>
  );
}
```

## 6. Protect pages

Check the session in each page with `session.require`, rather than in a
layout, because layouts don't render again on navigation. A Server Component
can't read its own URL, so `require` takes the page's path, where the sign-in
page sends the user back:

```tsx title="app/page.tsx"
import { session } from "../lib/auth/session";

export default async function Home() {
  const { user } = await session.require("/");
  return <h1>Welcome, {user.firstName}</h1>;
}
```

A signed-out user who opens `/orders` lands on `/login?redirectTo=%2Forders`.
To use another sign-in path, pass `loginPath` to `nextSession`.

## 7. Sign in

The sign-in page sends a user who is already signed in on to `redirectTo`,
with `session.redirectIfSignedIn`:

```tsx title="app/login/page.tsx"
import { session } from "../../lib/auth/session";
import { SignInForm } from "./sign-in-form";

export default async function Login({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  await session.redirectIfSignedIn((await searchParams).redirectTo);
  return <SignInForm />;
}
```

The form is a Client Component that calls the client's `signIn`:

```tsx title="app/login/sign-in-form.tsx"
"use client";

import { useState, type FormEvent } from "react";

import { useAuthClient } from "@monarcode/session-kit/react";

export function SignInForm() {
  const auth = useAuthClient();
  const [error, setError] = useState("");

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const form = new FormData(event.currentTarget);
    try {
      await auth.signIn({
        username: String(form.get("username")),
        password: String(form.get("password")),
      });
    } catch (failure) {
      // What the client's signIn option threw, from signInAction's error.
      setError(failure instanceof Error ? failure.message : "Sign-in failed");
    }
  }

  return (
    <form onSubmit={submit}>
      <label>
        Username
        <input name="username" autoComplete="username" />
      </label>
      <label>
        Password
        <input
          name="password"
          type="password"
          autoComplete="current-password"
        />
      </label>
      {error && <p role="alert">{error}</p>}
      <button>Sign in</button>
    </form>
  );
}
```

The form doesn't navigate after a sign-in. The session changed in the
browser, so `useMirrorAuth` renders the page again on the server, and
`redirectIfSignedIn` sends the user on. To try it, sign in as `emilys` with
the password `emilyspass`.

In this guide, the server signs in with your backend, so the user in the
cookie comes from the backend. If the browser has to sign in with the backend
itself, have `signInAction` take the tokens instead:
[Hybrid setup](https://session-kit.pages.dev/docs/server-rendering/hybrid) shows how.

## 8. Sign out

The client's `signOut()` signs out on the server through the session route,
which clears the cookie and calls your `revoke` option, if `createServerAuth`
has one. It then signs out this tab and tells the others. `useMirrorAuth`
calls `router.refresh()`, so `session.require` sends the user to the sign-in
page. Put a button like this one on any protected page:

```tsx title="app/sign-out-button.tsx"
"use client";

import { useAuthClient } from "@monarcode/session-kit/react";

export function SignOutButton() {
  const auth = useAuthClient();
  // A failed sign-out keeps the session, and shows in `state.error`.
  return (
    <button onClick={() => void auth.signOut().catch(() => {})}>
      Sign out
    </button>
  );
}
```

Without `revoke`, a copy of the cookie made before sign-out still works: see
[Sign-out](https://session-kit.pages.dev/docs/server-rendering/server-sessions#sign-out).

## Call your API

Your server code calls your API with `createAuthFetch` from
`@monarcode/session-kit/http`, which sends the request's access token to your
API's origin only. In a Server Component, pass it `session.readOnly()`, the
request's session that doesn't set cookies:

```tsx title="app/orders/page.tsx"
import { createAuthFetch } from "@monarcode/session-kit/http";
import { z } from "zod";

import { API } from "../../lib/auth/server";
import { session } from "../../lib/auth/session";

const orders = z.object({ carts: z.array(z.object({ id: z.number() })) });

export default async function Orders() {
  const { user } = await session.require("/orders");
  const authFetch = createAuthFetch(await session.readOnly(), {
    baseUrl: `${API}/`,
  });
  const response = await authFetch(`auth/carts/user/${user.id}`);
  if (!response.ok) throw new Error(`Orders failed (${response.status})`);
  const { carts } = orders.parse(await response.json());
  return <p>{carts.length} orders</p>;
}
```

Proxy refreshed the token before the render. A token that expired anyway
rejects with `REFRESH_FAILED`, and so does a 401 from your API, since a
Server Component can't save a new token: see
[Requests that can't set cookies](https://session-kit.pages.dev/docs/server-rendering/server-sessions#requests-that-cant-set-cookies).

In Server Functions and Route Handlers, pass `await session.writable()`
instead, the request's session that can set cookies. When your API answers
401 there, `authFetch` gets a new access token and saves it in the cookie. It
sends a `GET` or `HEAD` again with the new token, as
[After a 401](https://session-kit.pages.dev/docs/client/requests#after-a-401) explains.

With an HTTP client of your own, such as ky or axios, see
[Other HTTP clients](https://session-kit.pages.dev/docs/client/other-http-clients). A client without a
`fetch` option reads the token with `credentials.get()` on
`await session.readOnly()` or `await session.writable()`.

To call your API from the browser too, turn on `clientCredentials` in
`createServerAuth`: see
[The access token in the browser](https://session-kit.pages.dev/docs/server-rendering/server-sessions#the-access-token-in-the-browser).
The example app does this.

## Things to know

- **Writes only where Next allows them.** Use `signIn`, `signOut`,
  `updateUser` and `writable()` in Server Functions and Route Handlers only.
  In a Server Component they can't set the cookie, and `writable()` would
  refresh and then fail to save the new tokens, which spends a rotating
  refresh token.
- **One read per request.** Calls to `session` during one request read the
  cookie once, and a sign-in through `signIn` shows in `get()`.
- **Separate instances.** Next builds Proxy, Route Handlers, and pages with
  their Server Functions separately, so each has its own `serverAuth`, even
  on one server. They share no refresh. A matcher that covers every route
  that reads the session lets Proxy refresh first, so Route Handlers and
  Server Functions rarely need to.
- **A `basePath`.** Next doesn't add it to `fetch`, so the client's
  `endpoint` includes it: `"/app/api/session"`. Nor does Next add it to a
  Route Handler's redirects, so a Route Handler reads the session with `get`
  and answers 401, rather than calling `require`.
- **Rendering.** Reading cookies makes a page dynamic, and the root layout
  reads the session, so every page is dynamic. Next sends such pages with
  `Cache-Control: no-store`, and plain `use cache` can't read cookies.
- **The Node.js runtime.** Keep pages that read the session on the Node.js
  runtime, the default. Next might not pass Proxy's refreshed cookie on to
  Edge runtime pages.
- **Other tabs.** Signing in or out in one tab reaches the others, which ask
  the server for the session and render their pages again: see
  [How tabs stay in step](https://session-kit.pages.dev/docs/server-rendering#how-tabs-stay-in-step).
- **Deploying.** Several server instances, the cookie's size, and plain http
  during development are covered in
  [Server sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions).

## Next steps

- [Server sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions): the cookie, the
  secret, signing out, and the limits every server-rendered setup shares.
- [Hybrid setup](https://session-kit.pages.dev/docs/server-rendering/hybrid): sign in from the browser
  and call your API there, with the session still on the server.
- [Using the client](https://session-kit.pages.dev/docs/client): what the browser's client can do.
- [Use Effect on the server](https://session-kit.pages.dev/docs/effect/server): run Effects with a
  request's session.