Create an API route
- App Router
- Pages Router
Create a route handler at
app/api/auth/[...all]/route.ts and re-export the HTTP method handlers produced by toNextJsHandler.app/api/auth/[...all]/route.ts
toNextJsHandler also exports PATCH, PUT, and DELETE handlers. The destructured form above is the minimal configuration required for most use cases.You can change the base path in your Better Auth configuration, but
/api/auth is the recommended default.Create a client
Create an auth client instance and export it from a shared module. Import frombetter-auth/react to get React-specific helpers such as the useSession hook.
lib/auth-client.ts
useSession hook
app/dashboard/page.tsx
Server-side session access
Theauth.api object exposes every Better Auth endpoint as a callable function, including all plugin endpoints.
Server components (RSC)
app/dashboard/page.tsx
Server actions
app/actions.ts
Server action cookies
When you call functions that set cookies (such assignInEmail or signUpEmail) inside a server action, cookies are not set automatically because Next.js requires the cookies helper from next/headers.
Use the nextCookies plugin to handle this transparently:
lib/auth.ts
app/actions.ts
Route protection
In Next.js middleware it is recommended to only check for the existence of a session cookie for redirects — making database calls in middleware adds latency to every request. Perform full session validation inside individual pages or route handlers instead.Next.js 16+ (Proxy)
Next.js 16 replaces middleware with a “proxy”. The Node.js runtime is available by default, enabling full session validation.- Full session validation
proxy.ts
Migrating from middleware: Rename
middleware.ts to proxy.ts and rename the exported function from middleware to proxy. All Better Auth methods work identically. You can also use the Next.js codemod: npx @next/codemod@canary middleware-to-proxy .Next.js 15.2.0+ (Node.js runtime middleware)
From Next.js 15.2.0 you can opt into the Node.js runtime in middleware to make database calls directly.middleware.ts
Next.js 13–15.1.x (Edge runtime middleware)
Edge runtime middleware cannot make database calls. Use cookie-based checks for optimistic redirects, or fetch the session over HTTP.- HTTP fetch
Per-page auth checks
For the strongest security, validate the session inside each protected page:app/dashboard/page.tsx