# Quickstart for Next.js

> Run the tensile-auth server, proxy its routes through a Next.js app, and protect a page with the TypeScript SDK.

From `docs/guide-node.md` in tensile-tools/tensile-auth at commit `e66760d` (v0.4.1-7-ge66760d). The HTML page is https://auth.tensile.tools/docs/get-started/quickstart-nextjs.

This guide takes a Next.js app from `npm install` to passkey sign-in, a page that needs a recent proof, an agent with its own token, and an action the agent can take only after its person approves it. Steps 1 to 6 give you a working sign-in, and take about 15 minutes. Hono apps, on Node, Bun, or Deno, and Express apps use the same server and the same calls; see [Hono and Express](/docs/get-started/quickstart-nextjs#hono-and-express).

The app never sees a password or a passkey. The tensile-auth server holds them, and the app does two things with `@tensile-tools/auth`:

- It proxies the browser routes under `/auth/` to the server, so sessions stay in `__Host-` cookies on the app's own origin.
- It checks each request with the server in one call, `POST /v1/check`, so a revocation applies to the next request.

## Before you start

You need:

- Node 22.18 or later.
- Docker, to run the server from its image. To run it from a checkout of this repository instead, you need Go 1.26 or later.
- A Next.js 16 app with the App Router. To create one, run `npx create-next-app@latest my-app --ts --app --no-src-dir --import-alias '@/*' --no-cache-components`. The pages in this guide read the request, so with Cache Components on, `next build` refuses each of them until you wrap it in `<Suspense>`.

The steps use `http://localhost:3000` for the app and `localhost:8080` for the server.

## Start the server

The server keeps everything in one SQLite file here. Run the same version of the server as of `@tensile-tools/auth`: they share version numbers, and the SDK warns when the server is older. This guide uses 0.4.1 of both.

1. Create a master key, which seals the server's signing keys:

   ```sh
   mkdir -p ~/tensile-auth-dev && openssl rand -base64 32 > ~/tensile-auth-dev/master_key
   ```

2. Start the server from its image, and leave it running:

   ```sh
   docker run -d --name tensile-auth \
     -p 127.0.0.1:8080:8080 \
     -v tensile-auth-data:/home/nonroot \
     -v "$HOME/tensile-auth-dev/master_key:/run/secrets/master_key:ro" \
     -e TENSILE_AUTH_DATABASE_URL=sqlite:///home/nonroot/auth.db \
     -e TENSILE_AUTH_MASTER_KEY_FILE=/run/secrets/master_key \
     -e TENSILE_AUTH_ORIGINS=http://localhost:3000 \
     -e TENSILE_AUTH_PRESET=passkey-only@1 \
     -e TENSILE_AUTH_PASSWORDS__ENABLED=false \
     ghcr.io/tensile-tools/tensile-auth-server:v0.4.1
   ```

   The database lives in the Docker volume `tensile-auth-data`, so it survives `docker rm`. `passkey-only@1` needs no mail server. `TENSILE_AUTH_ORIGINS` must be your app's origin exactly: the server refuses any request for another origin.

3. Wait until the server is ready. Its health check, `/readyz`, answers on the ops port inside the container, and `health` asks it:

   ```sh
   until docker exec tensile-auth /tensile-auth-server health; do sleep 1; done
   ```

   It prints `ready` once the database is migrated and the server serves. Don't poll an API route instead: `/readyz` also checks the database and the schema.

4. Create an app key for your app's backend:

   ```sh
   docker exec tensile-auth /tensile-auth-server app-key create my-app
   ```

   The key starts with `tsx_` and is shown once. Keep it for step 3.

To see the server's log, run `docker logs tensile-auth`. To stop it, run `docker stop tensile-auth`, and `docker start tensile-auth` to start it again with the same database.

### Run the server with Go

In a checkout of this repository, at the tag that matches your SDK, for example `git checkout v0.4.1`:

1. Create the master key as in step 1 above.

2. Set the configuration for this shell:

   ```sh
   export TENSILE_AUTH_DATABASE_URL="sqlite://$HOME/tensile-auth-dev/auth.db"
   export TENSILE_AUTH_MASTER_KEY_FILE="$HOME/tensile-auth-dev/master_key"
   export TENSILE_AUTH_ORIGINS=http://localhost:3000
   export TENSILE_AUTH_PRESET=passkey-only@1
   export TENSILE_AUTH_PASSWORDS__ENABLED=false
   export TENSILE_AUTH_LISTEN=127.0.0.1:8080
   export TENSILE_AUTH_OPS_LISTEN=127.0.0.1:9090
   ```

3. Create the database and an app key for your app's backend:

   ```sh
   go run ./cmd/tensile-auth-server migrate
   go run ./cmd/tensile-auth-server app-key create my-app
   ```

4. Start the server, and leave it running:

   ```sh
   go run ./cmd/tensile-auth-server serve
   ```

   It logs `serving` when it's ready, and `curl http://127.0.0.1:9090/readyz` answers 200.

Don't use `tensile-auth-server dev` here: `dev` keeps app keys nowhere, so it serves no `/v1/` API.

## Install the SDK

Install `@tensile-tools/auth` and the browser client, `@tensile-tools/auth-client`, in your app:

```sh
npm install @tensile-tools/auth @tensile-tools/auth-client
```

`@tensile-tools/auth` has no runtime dependencies. It uses only `fetch`, Web Crypto, and Web Streams.

## Configure the adapter

Put the server's URL and the app key in `.env.local`, which Next.js keeps out of the browser bundle:

```sh
TENSILE_AUTH_URL=http://localhost:8080
TENSILE_AUTH_APP_KEY=tsx_...
```

Then create the adapter once:

```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',
  stepUp: '/step-up',
})
```

The app key lets the backend call the server. It never acts for a person by itself, and it never reaches the browser.

## Proxy the browser routes

The browser client calls `/auth/` on your app's origin. Forward those calls to the server:

```ts
// app/auth/[...path]/route.ts
import { auth } from '@/lib/auth'

export const { GET, POST } = auth.proxy
```

The proxy forwards only the library's cookies and a fixed list of headers, adds the app key itself, and answers any other path with 404.

## Add `gate` to every page

Server Components can't see a request's method, so the adapter checks the pages that `gate` doesn't cover as unsafe requests, which a link from another site can't open. `gate` also carries rotated session cookies, and sends signed-out visitors of the pages in `matcher` to `signIn`:

```ts
// proxy.ts, next to app/
import { auth } from '@/lib/auth'

export const proxy = auth.gate({ matcher: ['/settings', '/security'] })

export const config = { matcher: ['/((?!_next/|auth/|api/|favicon.ico).*)'] }
```

## Sign in, and protect a page

The sign-in and sign-up pages use the elements: drop-in screens that run the passkey ceremony against `/auth/`. The server serves them under `/auth/client/elements/`, and the proxy from step 4 forwards that path, so the pages need no build step and no client code.

Tell TypeScript about the two elements, with the attributes the pages set:

```ts
// tensile-elements.d.ts, next to app/
import type { DetailedHTMLProps, HTMLAttributes } from 'react'

type TensileElement = DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement> & {
  redirect?: string
  methods?: 'passkey' | 'password' | 'both'
  theme?: 'light' | 'dark' | 'auto'
  'app-name'?: string
  'sign-in-href'?: string
  'sign-up-href'?: string
}

declare module 'react' {
  namespace JSX {
    interface IntrinsicElements {
      'tensile-sign-in': TensileElement
      'tensile-sign-up': TensileElement
    }
  }
}
```

Each page renders its element and loads the elements' module. After sign-in, the element opens `redirect`, which the page takes from `?next=` when it is a path on your origin:

```ts
// lib/next-path.ts

// Browsers read `\` as `/` and drop tabs and newlines, so
// `/\evil.example` reaches another host. Resolving a path removes dot
// segments, so `/.//evil.example` becomes `//evil.example`, another
// host too. Only a path that resolves to one leading `/` passes.
export function nextPath(next: string | null | undefined): string {
  if (!next?.startsWith('/') || /[\u0000-\u001f\u007f\\]/.test(next)) return '/'
  const base = 'https://app.invalid'
  try {
    const u = new URL(next, base)
    return u.origin === base && !u.pathname.startsWith('//') ? u.pathname + u.search + u.hash : '/'
  } catch {
    return '/'
  }
}
```

```tsx
// app/sign-in/page.tsx
import { nextPath } from '@/lib/next-path'

type Props = { searchParams: Promise<{ next?: string }> }

export default async function SignIn({ searchParams }: Props) {
  const next = nextPath((await searchParams).next)
  return (
    <main>
      <tensile-sign-in app-name="My app" methods="passkey" redirect={next}
        sign-up-href={`/sign-up?next=${encodeURIComponent(next)}`} />
      <script type="module" src="/auth/client/elements/index.js" async />
    </main>
  )
}
```

```tsx
// app/sign-up/page.tsx
import { nextPath } from '@/lib/next-path'

type Props = { searchParams: Promise<{ next?: string }> }

export default async function SignUp({ searchParams }: Props) {
  const next = nextPath((await searchParams).next)
  return (
    <main>
      <tensile-sign-up app-name="My app" methods="passkey" redirect={next}
        sign-in-href={`/sign-in?next=${encodeURIComponent(next)}`} />
      <script type="module" src="/auth/client/elements/index.js" async />
    </main>
  )
}
```

`methods="passkey"` matches the `passkey-only@1` preset from step 1; with a preset that allows passwords, leave it out to offer both. The `async` attribute lets React load the module after a client-side navigation as well as on the first load. To change the text, colours, or fonts, see [the elements' README](/docs/reference/elements).

A page that needs a person calls `auth.require`. It returns the principal, or sends a signed-out visitor to `/sign-in?next=/settings`:

```tsx
// app/settings/page.tsx
import { auth } from '@/lib/auth'

export default async function Settings() {
  const p = await auth.require({ action: 'settings.view', human: true })
  return (
    <main>
      <h1>Settings</h1>
      <p>Signed in as {p.user}</p>
    </main>
  )
}
```

`p.user` is the server's ID for the person. Store it in your own user table, for example as `authUserId`, to link your data to them.

To check it, run `npm run dev` and open `http://localhost:3000/settings`. It sends you to the sign-in page. Follow its sign-up link, create an account with a passkey, and the settings page shows your user ID. After the session ends, the sign-in page signs you in with the same passkey. You have a working sign-in.

## Ask for a recent proof

For a sensitive page, ask for a passkey proof from the last 10 minutes. A session older than that goes to `stepUp` and comes back:

```tsx
// app/security/page.tsx
import { auth } from '@/lib/auth'

export default async function Security() {
  const p = await auth.require({ action: 'security.view', human: true, within: '10m' })
  return <main><h1>Security</h1><p>Confirmed at {p.authenticated_at}</p></main>
}
```

```tsx
// app/step-up/page.tsx
'use client'

import { createAuthClient } from '@tensile-tools/auth-client'
import { nextPath } from '@/lib/next-path'

export default function StepUp() {
  return (
    <button onClick={async () => {
      const r = await createAuthClient().stepUp()
      if (r.outcome === 'ok') location.href = nextPath(new URLSearchParams(location.search).get('next'))
    }}>Confirm with a passkey</button>
  )
}
```

## Give an agent its own token

An agent, such as a coding assistant, gets its own token, delegated from the person's session. It never uses the person's cookie:

```ts
// app/api/agents/route.ts
import { auth } from '@/lib/auth'

export const POST = auth.route(async () => {
  await auth.require({ action: 'agent.create', human: true })
  const me = auth.as(await auth.subject())
  const agent = await me.agents.create({ name: 'My agent', scopes: [] })
  const { token } = await me.agents.delegate(agent.id, { scopes: [], ttl: '1h' })
  return Response.json({ agent: agent.id, token }, { status: 201 })
})
```

`auth.as(subject)` acts as the signed-in person: the server checks the person's own credential, so the app key alone can't create an agent for anyone. The token starts with `tsa_` and is shown once. The agent sends it as `Authorization: Bearer tsa_...`.

## Let the person approve an agent's action

Some actions need the person, but an agent can ask for them. `auth.approvable` refuses the agent with `human_required` and an approval to wait for, and lets it through once the person approves exactly that action:

```ts
// app/api/repos/[id]/route.ts
import { auth } from '@/lib/auth'

type Ctx = { params: Promise<{ id: string }> }

export const DELETE = auth.approvable<Ctx>(
  { action: 'repo.delete', human: true },
  async (_req, { params }) => {
    const { id } = await params
    return { kind: 'repo.delete', resource: id, summary: `Delete the repository ${id}` }
  },
  async (_req, { principal }) => Response.json({ deleted: true, by: principal.agent ?? principal.user }),
)
```

The flow:

1. The agent calls `DELETE /api/repos/42` with its token, and gets 403 with `challenge.approval.id` in the problem.
2. The agent shows the person your approval page, `http://localhost:3000/approve/<id>`. Asking again returns the same approval, so the person sees one request.
3. The person opens the page, reads the summary, and approves with their passkey. The page calls `GET /auth/approvals/<id>`, then `POST /auth/approvals/<id>/begin` and `/finish` with the passkey's answer; `sdk/examples/next/app/approve/[id]/page.tsx` is a complete page.
4. The agent retries the same request once, with the header `Tensile-Approval: <id>` and the `Prefer` value from `challenge.approval.wait_hint`, for example `Prefer: wait=50`. The route holds the retry until the person decides, then runs once, and only for `repos/42`. A wait that runs out answers `approval_pending`, and the agent retries.

An approval lasts 5 minutes. For an agent that runs in the background, set `approvalTtl`, from `'1m'` to `'24h'`, on the need.

The route holds a retry for up to `approvalWait` seconds: 50 by default under `next start` or `next dev`, below the common 60-second proxy idle timeout. On Vercel and other serverless platforms it defaults to 0, and the refusal has no `wait_hint`: the agent retries after `Retry-After` instead. To wait there, pass `{ wait: 25 }` as a fourth argument to `auth.approvable`, and `export const maxDuration = 30` from the route file; keep `maxDuration` at least the wait plus 5 seconds. See [wait for an approval](/docs/sdk/core#wait-for-an-approval).

## Email and password sign-up

This guide uses passkeys only. To offer email and password sign-up as well:

1. Give the server a preset with passwords and a mailer. In the `docker run` command of step 1, leave out `TENSILE_AUTH_PRESET` and `TENSILE_AUTH_PASSWORDS__ENABLED`, so the server uses `standard@1`, and add `TENSILE_AUTH_PASSWORDS__MAILER_URL`. For a mailbox on your computer, see [Mail](/docs/server/configure#mail). To change a container's settings, remove it with `docker rm -f tensile-auth` and run it again: the database stays in the volume.
2. Leave out `methods="passkey"` on the elements, so they offer both.

The confirmation email links to `/auth/password/confirm` on your app's origin, the first origin in `TENSILE_AUTH_ORIGINS`, and a reset email to `/auth/password/reset`. The proxy from step 4 forwards both to the server, which serves the pages, so your app needs no confirmation or reset page. Opening a page changes nothing: it posts the code only when the person chooses **Confirm**, so a mail scanner that opens the link can't spend it. In a browser other than the one that signed up, the page also asks for the password.

With `standard@1`, the account exists only after the person confirms the address. One client address can start 5 sign-ups, then 1 every 12 minutes; see [Rate limits](/docs/server/configure#rate-limits).

## Hono and Express

A Hono app, on Node, Bun, or Deno, or an Express app on Node, uses the same server, app key, and browser routes as the Next.js app. Step 1 is the same. The other steps differ in these ways:

| Step | Next.js | Hono | Express |
|---|---|---|---|
| 2. Install | `@tensile-tools/auth` | `@tensile-tools/auth` and `hono`, and `@hono/node-server` on Node | `@tensile-tools/auth` and `express` |
| 3. Configure | `tensile` from `@tensile-tools/auth/next`, with `signIn` and `stepUp` | `tensile` from `@tensile-tools/auth/hono`, without `signIn` and `stepUp` | `tensile` from `@tensile-tools/auth/express`, without `signIn` and `stepUp` |
| 4. Proxy the browser routes | `app/auth/[...path]/route.ts` | `app.all('/auth/*', auth.proxy())` | `app.use(auth.proxy())`, before any body parser |
| 5. Add `gate` | `proxy.ts` | No `gate`: each route's middleware checks it and copies rotated cookies | No `gate`, as for Hono |
| 6. Protect a route | `auth.require(need)`, which sends a signed-out visitor to `signIn` | `auth.need(need)`, which answers the server's problem, for example 401 when signed out. For a page, use `auth.authenticate()` and redirect yourself | `auth.need(need)` and `auth.authenticate()`, as for Hono |
| 8. Act for the person | `auth.as(await auth.subject())` | `auth.as(c)` | `auth.as(req)` |
| 9. Approvals | `auth.approvable(need, describe, handler)` | `auth.approvable(need, describe)` as middleware | `auth.approvable(need, describe)` as middleware |

The sign-in and sign-up pages work as in step 6: each renders an element and loads `/auth/client/elements/index.js`, which the proxy forwards to the server. Add `@tensile-tools/auth-client` only when your own browser code calls the client, for example for the step-up button in step 7 or a React app.

### A complete Hono app

1. Install the SDK and Hono. With Bun, run `bun add @tensile-tools/auth hono`. With Deno, run `deno add npm:@tensile-tools/auth npm:hono`. With Node, run `npm install @tensile-tools/auth hono @hono/node-server`.

2. Put the server's URL and the app key from step 1 in `.env`:

   ```sh
   TENSILE_AUTH_URL=http://localhost:8080
   TENSILE_AUTH_APP_KEY=tsx_...
   ```

3. Copy `nextPath` from step 6 into `next-path.ts`, and write the app:

   ```ts
   // server.ts
   import { Hono } from 'hono'
   import { html } from 'hono/html'
   import { tensile, type TensileEnv } from '@tensile-tools/auth/hono'
   import { nextPath } from './next-path.ts'

   const auth = tensile({ url: process.env.TENSILE_AUTH_URL!, appKey: process.env.TENSILE_AUTH_APP_KEY! })
   const app = new Hono<TensileEnv>()

   // The browser routes, the elements, and the pages that email links open.
   app.all('/auth/*', auth.proxy())

   app.get('/sign-in', c => {
     const next = nextPath(c.req.query('next'))
     return c.html(html`<!doctype html><meta charset="utf-8"><title>Sign in</title>
       <tensile-sign-in app-name="My app" methods="passkey" redirect="${next}"
         sign-up-href="/sign-up?next=${encodeURIComponent(next)}"></tensile-sign-in>
       <script type="module" src="/auth/client/elements/index.js"></script>`)
   })

   app.get('/sign-up', c => {
     const next = nextPath(c.req.query('next'))
     return c.html(html`<!doctype html><meta charset="utf-8"><title>Sign up</title>
       <tensile-sign-up app-name="My app" methods="passkey" redirect="${next}"
         sign-in-href="/sign-in?next=${encodeURIComponent(next)}"></tensile-sign-up>
       <script type="module" src="/auth/client/elements/index.js"></script>`)
   })

   // A page: a visitor who isn't signed in goes to the sign-in page.
   app.get('/settings', auth.authenticate(), c => {
     const p = c.get('principal')
     if (p?.kind !== 'human') return c.redirect(`/sign-in?next=${encodeURIComponent(c.req.path)}`)
     return c.html(html`<!doctype html><meta charset="utf-8"><title>Settings</title>
       <h1>Settings</h1><p>Signed in as ${p.user}</p>`)
   })

   // An API route: anyone else gets the server's problem, for example 401 when signed out.
   app.get('/api/me', auth.need({ action: 'me.read', human: true }), c => c.json({ user: c.get('principal')!.user }))

   export default app
   ```

   `hono/html` escapes each value it inserts, so `next` can't add markup.

4. Start the app on port 3000, the origin you gave the server:

   - **Bun.** Run `bun run server.ts`. Bun reads `.env` and serves the default export on port 3000.
   - **Deno.** Run `deno serve --env-file --allow-net --allow-env --port 3000 server.ts`.
   - **Node.** Replace `export default app` with `serve({ fetch: app.fetch, port: 3000 })`, imported from `@hono/node-server`, and run `node --env-file=.env server.ts`.

5. Open `http://localhost:3000/settings`. It sends you to the sign-in page; sign up with a passkey, and the settings page shows your user ID.

The Hono adapter's tests run on Node and Deno, not on Bun. Under Bun and `@hono/node-server`, the adapter reads the client's address from the socket; see [the client's address](/docs/sdk/hono#the-clients-address).

### Express

```ts
import express from 'express'
import { tensile } from '@tensile-tools/auth/express'

const auth = tensile({ url: process.env.TENSILE_AUTH_URL!, appKey: process.env.TENSILE_AUTH_APP_KEY! })
const app = express()

app.use(auth.proxy()) // before any body parser
app.get('/api/me', auth.need({ action: 'me.read', human: true }), (req, res) => res.json({ user: req.principal!.user }))
app.listen(3000)
```

Each adapter's README lists its calls: [Hono](/docs/sdk/hono), [Express](/docs/sdk/express), and [Next.js](/docs/sdk/nextjs).

## Before you deploy

- Use `https://` origins. Passkeys and `Secure` cookies need `https://` outside localhost, and the server refuses an `http://` origin elsewhere.
- Behind a proxy or on Vercel, set `trustProxy`, so rate limits see each client's address; see [the client's address](/docs/sdk/nextjs#the-clients-address).
- In a long-running Node process, you can turn on the cache with `cache: true`, which serves allowed checks for up to 30 seconds and clears them within 100 milliseconds of a revocation. Leave it off on serverless runtimes; see [cache checks](/docs/sdk/cache).
- To decide sign-ups or name your own user IDs, set the server's `hooks.url`, and answer each hook with `auth.webhooks.answer(event, answer)`.
- Run the server with Postgres for more than one replica; see [`examples/server`](/docs/server/install) and the server design.
