Skip to Content

Next.js

Keep the session in an encrypted cookie with the Next.js App Router, where Server Components read it and Proxy refreshes it.

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 work with it. Server rendering explains how the pieces fit. A complete app is in examples/next-app.

Before you begin

  • Next.js 16 with the App Router, which needs Node.js 20.9 or newer. See 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 says how to keep and rotate it.
  • The code signs in with DummyJSON's test backend, as Getting started does. Replace its URLs with your backend's.

Installation

To install the packages, run the following command:

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:

lib/auth/server.ts
import "server-only";
import {  } from "@monarcode/session-kit/server";
import {  } from "zod";

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

const  = .({ : .(), : .() });
const  = .({ : .(), : .() });

export const  = ({
  : "app",
  : ,
  : ..!,
  : async ({ ,  }) => {
    const  = await (`${}/auth/refresh`, {
      : "POST",
      ,
      : { "Content-Type": "application/json" },
      : .({  }),
    });
    // DummyJSON rejected the refresh token: sign out.
    if (. === 401 || . === 403) return null;
    if (!.) throw new (`Refresh failed (${.})`);
    return .(await .());
  },
});

/** Signs in with your backend, from the server. */
export async function (: string, : string) {
  const  = await (`${}/auth/login`, {
    : "POST",
    : { "Content-Type": "application/json" },
    : .({ ,  }),
  });
  const : unknown = await .().(() => null);
  if (!.) {
    // The backend says why, such as wrong credentials, in `message`.
    const  = .({ : .() }).();
    throw new (
      .
        ? ..
        : `Sign-in failed (${.})`,
    );
  }
  return { ....(), : .() };
}

server-only comes with Next, so there's nothing to install for it. 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:

lib/auth/session.ts
import "server-only";
import {  } from "@monarcode/session-kit/next";
import {  } from "next/headers";
import {  } from "next/navigation";

import {  } from "./server";

export const  = (, { ,  });

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:

proxy.ts
import { , type  } from "next/server";

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

export function (: ) {
  return .(, .());
}

export const  = {
  : ["/((?!_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 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:

app/api/session/route.ts
import {  } from "@monarcode/session-kit/next";
import {  } from "next/headers";

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

export const { ,  } = (, {  });

The session route answers your own site's pages only, so another site can't sign the user out: see 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:

app/actions.ts
"use server";

import {  } from "zod";

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

const  = .({ : .(), : .() });

export async function (: unknown) {
  const { ,  } = .();
  try {
    const  = await (, );
    return { : await .() };
  } catch () {
    return {
      :  instanceof  ? . : "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:

lib/auth/client.ts
import { , type  } from "@monarcode/session-kit";

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

export type  = <typeof >;

export function (:  | null) {
  return ({
    : "app",
    ,
    : "/api/session",
    : async (: { : string; : string }) => {
      const  = await ();
      if ("error" in ) throw new (.);
      return .;
    },
  });
}

export type  = <typeof >;

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:

app/providers.tsx
"use client";

import type {  } from "react";

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

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

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

export function (: {
  :  | null;
  : ;
}) {
  const  = ();
  const  = ({
    : ,
    : .,
    : () => .(),
  });
  return < ={}>{.}</>;
}

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

app/layout.tsx
import type {  } from "react";

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

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

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:

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

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

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:

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

export default async function ({
  ,
}: {
  : <<string, string | string[] | undefined>>;
}) {
  await .((await ).redirectTo);
  return < />;
}

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

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

import { , type  } from "react";

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

export function () {
  const  = ();
  const [, ] = ("");

  async function (: <>) {
    .();
    const  = new (.);
    try {
      await .({
        : (.("username")),
        : (.("password")),
      });
    } catch () {
      // What the client's signIn option threw, from signInAction's error.
      ( instanceof  ? . : "Sign-in failed");
    }
  }

  return (
    < ={}>
      <>
        Username
        < ="username" ="username" />
      </>
      <>
        Password
        <
          ="password"
          ="password"
          ="current-password"
        />
      </>
      { && < ="alert">{}</>}
      <>Sign in</>
    </>
  );
}

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

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

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

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

Without revoke, a copy of the cookie made before sign-out still works: see 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:

app/orders/page.tsx
import {  } from "@monarcode/session-kit/http";
import {  } from "zod";

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

const  = .({ : .(.({ : .() })) });

export default async function () {
  const {  } = await .("/orders");
  const  = (await .(), {
    : `${}/`,
  });
  const  = await (`auth/carts/user/${.}`);
  if (!.) throw new (`Orders failed (${.})`);
  const {  } = .(await .());
  return <>{.} orders</>;
}

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.

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 explains.

With an HTTP client of your own, such as ky or axios, see 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. 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.
  • Deploying. Several server instances, the cookie's size, and plain http during development are covered in Server sessions.

Next steps

On this page