# Next.js adapter

> The App Router adapter: a proxy route, `require` in pages and actions, approvable handlers, and `gate` in proxy.ts.

From `sdk/next/README.md` in tensile-tools/tensile-auth at commit `e66760d` (v0.4.1-7-ge66760d). The HTML page is https://auth.tensile.tools/docs/sdk/nextjs.

The Next.js adapter of `@tensile-tools/auth`, for the App Router on the Node.js runtime. Next.js 16 or later is a peer dependency: the app installs it.

## Use it

```ts
// lib/auth.ts
import { tensile } from '@tensile-tools/auth/next'
export const auth = tensile({ url: process.env.TENSILE_AUTH_URL!, appKey: process.env.TENSILE_AUTH_APP_KEY!, signIn: '/sign-in' })

// app/auth/[...path]/route.ts
import { auth } from '@/lib/auth'
export const { GET, POST } = auth.proxy

// app/settings/page.tsx (imports auth the same way)
export default async function Settings() {
  const p = await auth.require({ action: 'settings.view', human: true })
  return <SettingsForm user={await db.user.findUniqueOrThrow({ where: { authUserId: p.user } })} />
}
```

| Part | What it does |
|---|---|
| `auth.proxy` | `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, and `OPTIONS` handlers that forward the browser routes. Export them from `app/auth/[...path]/route.ts`. To forward `/admin/` or the OAuth routes, set `routes` and add the matching catch-all route |
| `auth.principal()` | The principal, or `undefined` when signed out. Works in Server Components, Server Actions, and route handlers |
| `auth.require(need?)` | The principal, when it meets `need`. Otherwise a page or Server Action redirects to `signIn` for a 401, or to `stepUp` for a step-up challenge, with `?next=` set to the page. Other refusals throw a `ProblemError`, which the nearest error boundary renders. Inside `auth.route`, every refusal becomes a problem response instead |
| `auth.route(handler)` | Wraps a route handler, so that `require` inside it answers problems, and the server's cookies reach its response |
| `auth.approvable(need, describe, handler, options?)` | A route handler that an agent may ask its human to approve. `handler` gets `ctx.principal`. With `Prefer: wait=N` on the retry, it holds the request until the person decides, for at most `approvalWait` seconds, or `options.wait` for this route, and ends the wait when `req.signal` aborts |
| `auth.subject()`, `auth.as(subject)` | Calls on the person's behalf: `auth.as(await auth.subject()).agents.create({name, scopes})` |
| `auth.gate(options?)` | A `proxy.ts` function that attests each request's method to the pages, carries rotated cookies, and redirects signed-out navigations to `signIn` early. It never replaces `require`, because it can't see which need a page declares |

Options of `tensile`, beyond the core's: `signIn` (required), `stepUp` (defaults to `signIn`), `appUrl` (defaults to the request's host), `routes`, `trustProxy`, `trustedProxies`, and `clientIp`.

On Vercel, `approvalWait` defaults to 0, so an agent's retry answers at once and the agent retries after `Retry-After`. To hold it for the person's tap, set the wait and the function's limit together, with `maxDuration >= approvalWait + 5`:

```ts
// app/api/repos/[id]/route.ts
export const maxDuration = 30
export const DELETE = auth.approvable<Ctx>(need, describe, handler, { wait: 25 })
```

See [wait for an approval](/docs/sdk/core#wait-for-an-approval).

## The client's address

The server uses the client's address for rate limits and the audit log. Anyone who connects to the app directly can send `X-Forwarded-For` and `X-Real-IP`, so the adapter reads a forwarded header only when you name it in `trustProxy`:

| `trustProxy` | The header the adapter reads |
|---|---|
| Unset or `false` | None |
| `{ header: 'x-forwarded-for', hops: n }` | The `n`th `X-Forwarded-For` entry from the right, for `n` proxies in a chain |
| `{ header: 'x-real-ip' }` | `X-Real-IP`, for a proxy that sets it |
| `true` | Shorthand for `x-forwarded-for` with 1 hop |
| A number `n` | Shorthand for `x-forwarded-for` with `n` hops |

The adapter reads only the header named. It never falls back from one header to the other, so a client-sent `X-Forwarded-For` can't override the `X-Real-IP` your proxy sets.

Next.js doesn't expose the socket's address, so without `trustProxy` the checks send no address, and with it the adapter reads the header on every request. The adapter can't tell your platform's proxy from a client. Set `trustProxy` only when the platform overwrites the header on every request, so a client can't reach the app with its own value. Vercel overwrites `X-Forwarded-For` and `X-Real-IP`, so on Vercel use `trustProxy: true`. Behind your own load balancer, make sure it replaces `X-Forwarded-For` rather than appending to it, or count its hops, and make sure clients can't reach the app around it.

`trustedProxies` lists your proxies' own addresses as CIDRs. Next.js has no socket address to check against it, so it only shortens the walk along `X-Forwarded-For`.

When you set `trustedProxies`, the walk along `X-Forwarded-For` also stops at the first entry outside them, and an entry that isn't an IP address stops it too, as in `authhttp`. A configuration that isn't valid, such as `hops: 0` or a malformed CIDR, throws when you create the adapter.

To read the address another way, pass `clientIp`, which overrides both options.

## Add `gate` on every page

Server Components and Server Actions see the request's headers, but not its method or URL. Cross-origin protection applies only to unsafe methods, and a Server Action is a POST. So the adapter checks a request it rebuilds from headers as a POST, unless `gate` in `proxy.ts`, which sees the real request, attests its method. The attestation carries a random token that lives only in the server process, and `gate` overwrites it on every request, so a client can't forge it. A Server Action is always checked as a POST.

Without `gate`, every page render is checked as unsafe: a same-site visit works, but a link to the page from another site is refused with `cross_origin`.

`gate` also:

- carries a session cookie that the server rotates. Server Components can't set cookies, so without `gate` a page-only app signs a person out when the old cookie's grace period ends. Route handlers wrapped in `auth.route` and the proxy routes carry rotated cookies on their own.
- sets the `x-tensile-path` request header, so a page's check names the page's URL in the audit log.
- redirects signed-out navigations to the pages in `matcher` to `signIn`.

```ts
// proxy.ts
import { auth } from '@/lib/auth'
export const proxy = auth.gate({ matcher: ['/settings'] })
export const config = { matcher: ['/((?!_next/|auth/|api/|favicon.ico).*)'] }
```
