Mount authtempo in Next.js
For: a developer of a Next.js 16 app on the App Router.
What it does: the app serves the routes of authtempo under /auth, and reads the session in a server component. A person with no session goes to the sign-in page.
Before you start
Section titled “Before you start”- Node 22.18 or newer.
- A storage adapter for production. Getting started shows D1 and Postgres.
- Add the packages:
pnpm --filter my-app add @authtempo/core @authtempo/next. - Make the auth instance in a function, so
next buildreads no secret. - Mount the routes in
app/auth/[...path]/route.ts. - Read the session with
authSessionin a server component. - Protect paths with
authProxyinproxy.ts. - Set
BASE_URLandAUTH_SECRETin the environment of the server. - Read
GET /auth/sessionfrom the browser on every page, so the browser gets the renewed cookie.app/providers.tsxbelow makes this read.app/layout.tsxputs it around every page.- Copy both files. The server reads write nothing, so this browser read is the one that renews the cookie.
import { type Auth, createAuth, createMemoryAdapter, type MailPort } from "@authtempo/core";
/** * Your mail transport. Core calls `send` once per mail. Replace the body with * a call to your mail provider. Until then a sign-in request answers 500. */export const mail: MailPort = { async send() { throw new Error("my-app: no mail transport; replace mail.send in lib/auth.ts"); },};
/** * Next bundles each route handler and each page on its own, so each bundle can * hold its own copy of this module. The one auth instance (and its memory * storage) lives on globalThis, so every bundle of the process shares it. A * D1 or Postgres adapter shares its rows anyway. */const shared = globalThis as typeof globalThis & { __myAppAuth?: Auth };
/** * The auth instance of this app. Warning: the memory adapter keeps rows in * this process only, and they go at a restart. Use the D1 or the Postgres * adapter in production (the getting started tutorials show both). */export function createAppAuth(input: { baseURL: string; secret: string; mail: MailPort }): Auth { return createAuth({ baseURL: input.baseURL, secret: input.secret, trustedOrigins: [input.baseURL], storage: createMemoryAdapter(), mail: input.mail, });}
function required(name: string): string { const value = process.env[name]; if (!value) throw new Error(`my-app: set ${name}`); return value;}
/** The app's one auth instance, made at the first request from BASE_URL and AUTH_SECRET. A build reads neither. */export function getAuth(): Auth { shared.__myAppAuth ??= createAppAuth({ baseURL: required("BASE_URL"), secret: required("AUTH_SECRET"), mail, }); return shared.__myAppAuth;}import { authRouteHandlers } from "@authtempo/next";import { getAuth } from "../../../lib/auth";
// Every route of core under /auth, the default basePath.export const { GET, POST, OPTIONS } = authRouteHandlers(getAuth);import { authSession } from "@authtempo/next";import { headers } from "next/headers";import { getAuth } from "../lib/auth";
export default async function Home() { const session = await authSession(getAuth, await headers()); return ( <main> {session ? <p>Signed in as {session.user.email}</p> : <a href="/sign-in">Sign in</a>} </main> );}import { authProxy } from "@authtempo/next";
// A request to /account with no session cookie goes to /sign-in?next=/account.// The page reads the session itself; the proxy checks only that the cookie is present.export const proxy = authProxy({ protect: (pathname) => pathname.startsWith("/account"), signInPath: "/sign-in",});
export const config = { matcher: ["/account/:path*"] };SessionRenewal subscribes to the session store of @authtempo/react, so each page reads GET /auth/session in the browser. That read slides the session and sends the renewed cookie.
AuthErrorNotice reads the flow error that core sends to the app root, and shows it on every page.
"use client";import { type Client, createClient, ERRORS, type ErrorCode, errorText, type OAuthClientCode,} from "@authtempo/client";import { type AuthErrorCode, AuthProvider, useAuthError, useSession } from "@authtempo/react";import type { ReactNode } from "react";
// The API is this app's own origin: core is mounted under /auth.let browserClient: Client | null = null;function appClient(): Client { browserClient ??= createClient({ baseURL: typeof location === "undefined" ? "http://localhost:3000" : location.origin, }); return browserClient;}
/** * Subscribes to the session store on every page, so the browser reads * GET /auth/session. That read is the one that slides the session and sends * the renewed cookie: the server components read with no write, so without * this read a session ends at its first expiry. */function SessionRenewal(): null { useSession(); return null;}
/** * The text of a redirect error. A code of core's table takes the core text; * any other code is an OAuth code or `unexpected`, which the OAuth table answers. */function redirectText(code: NonNullable<AuthErrorCode>): string { return Object.hasOwn(ERRORS, code) ? errorText(code as ErrorCode) : errorText(code as OAuthClientCode, "oauth");}
/** * Core sends every browser flow failure to the app's URL with * `?auth_error=<code>`, such as a magic link that is spent. The read sits here, * so the text shows on whichever page the failure lands. */function AuthErrorNotice(): ReactNode { const code = useAuthError(); return code ? <p role="alert">{redirectText(code)}</p> : null;}
/** The client and the session store for every page. Tests pass a client of their own. */export function Providers({ children, client }: { children: ReactNode; client?: Client }) { return ( <AuthProvider client={client ?? appClient()}> <SessionRenewal /> <AuthErrorNotice /> {children} </AuthProvider> );}import type { ReactNode } from "react";import { Providers } from "./providers";
export const metadata = { title: "authtempo Next.js example" };
export default function RootLayout({ children }: { children: ReactNode }) { return ( <html lang="en"> <body> <Providers>{children}</Providers> </body> </html> );}How it behaves
Section titled “How it behaves”- A server component cannot set a cookie, so
authSessionleaves the sliding refresh for the browser. Only the browser’s read ofGET /auth/sessionsends the renewed cookie. - An app with no such read loses the cookie at its first
Max-Age, and the person must sign in again. - Without
auth, the proxy checks only that a session cookie is present, or a bearer that starts withts_. The page checks the session. Never trust the proxy alone. - The session cookie is
__Host-tempo_sessionby default. SetcookieNameon the proxy when the config of core sets another name. - Next 16 renamed middleware to proxy. For a file named
middleware.ts,next buildwarns that the “middleware” file convention is deprecated.
If it fails
Section titled “If it fails”origin_not_trusted: the page posts from an origin that is notBASE_URL.unauthorized: no session. The proxy sends the person to the sign-in page.