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.
On this page
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. Express and Hono apps use the same server and the same calls; see Express and Hono.
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.
- Go 1.26 or later, to run the server from this repository. To run it with Docker and Postgres instead, see
examples/server. - 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 buildrefuses 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. In a checkout of this repository:
-
Create a master key, which seals the server’s signing keys:
Shellmkdir -p ~/tensile-auth-dev && openssl rand -base64 32 > ~/tensile-auth-dev/master_key -
Set the configuration for this shell:
Shellexport 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:9090passkey-only@1needs no mail server.TENSILE_AUTH_ORIGINSmust be your app’s origin exactly: the server refuses any request for another origin. -
Create the database and an app key for your app’s backend:
Shellgo run ./cmd/tensile-auth-server migrate go run ./cmd/tensile-auth-server app-key create my-appThe key starts with
tsx_and is shown once. Keep it for step 3. -
Start the server, and leave it running:
Shellgo run ./cmd/tensile-auth-server serveIt logs
servingwhen it’s ready.
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:
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:
TENSILE_AUTH_URL=http://localhost:8080
TENSILE_AUTH_APP_KEY=tsx_...Then create the adapter once:
// 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:
// app/auth/[...path]/route.ts
import { auth } from '@/lib/auth'
export const { GET, POST } = auth.proxyThe 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:
// 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:
// 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:
// 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 '/'
}
}// 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>
)
}// 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.
A page that needs a person calls auth.require. It returns the principal, or sends a signed-out visitor to /sign-in?next=/settings:
// 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:
// 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>
}// 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:
// 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:
// 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:
- The agent calls
DELETE /api/repos/42with its token, and gets 403 withchallenge.approval.idin the problem. - 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. - The person opens the page, reads the summary, and approves with their passkey. The page calls
GET /auth/approvals/<id>, thenPOST /auth/approvals/<id>/beginand/finishwith the passkey’s answer;sdk/examples/next/app/approve/[id]/page.tsxis a complete page. - The agent retries the same request once, with the header
Tensile-Approval: <id>and thePrefervalue fromchallenge.approval.wait_hint, for examplePrefer: wait=50. The route holds the retry until the person decides, then runs once, and only forrepos/42. A wait that runs out answersapproval_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.
Before you deploy
- Use
https://origins. Passkeys andSecurecookies needhttps://outside localhost, and the server refuses anhttp://origin elsewhere. - Behind a proxy or on Vercel, set
trustProxy, so rate limits see each client’s address; see the client’s 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. - To decide sign-ups or name your own user IDs, set the server’s
hooks.url, and answer each hook withauth.webhooks.answer(event, answer). - Run the server with Postgres for more than one replica; see
examples/serverand the server design.