Skip to content

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.

  • Node 22.18 or newer.
  • A storage adapter for production. Getting started shows D1 and Postgres.
  1. Add the packages: pnpm --filter my-app add @authtempo/core @authtempo/next.
  2. Make the auth instance in a function, so next build reads no secret.
  3. Mount the routes in app/auth/[...path]/route.ts.
  4. Read the session with authSession in a server component.
  5. Protect paths with authProxy in proxy.ts.
  6. Set BASE_URL and AUTH_SECRET in the environment of the server.
  7. Read GET /auth/session from the browser on every page, so the browser gets the renewed cookie.
    • app/providers.tsx below makes this read. app/layout.tsx puts it around every page.
    • Copy both files. The server reads write nothing, so this browser read is the one that renews the cookie.
lib/auth.ts
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;
}
app/auth/[...path]/route.ts
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);
app/page.tsx
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>
);
}
proxy.ts
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.

app/providers.tsx
"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>
);
}
app/layout.tsx
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>
);
}
  • A server component cannot set a cookie, so authSession leaves the sliding refresh for the browser. Only the browser’s read of GET /auth/session sends 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 with ts_. The page checks the session. Never trust the proxy alone.
  • The session cookie is __Host-tempo_session by default. Set cookieName on the proxy when the config of core sets another name.
  • Next 16 renamed middleware to proxy. For a file named middleware.ts, next build warns that the “middleware” file convention is deprecated.