Standard patterns for using Better Auth in Next.js 16+ App Router projects, including server and client integration, JWT plugin usage, and attaching tokens to backend API calls in a reusable way.
Use this Skill whenever you are:
Authorization: Bearer <token>) to
frontend → backend API calls.This Skill must be generic enough to work for any Next.js + Better Auth project, not just a single repository.
Do not assume a specific database or UI library. The patterns must focus on auth, not styling or persistence.
The typical structure for Better Auth in Next.js includes:
Auth config / server instance (e.g. lib/auth.ts):
Auth route handler (e.g. app/api/auth/[...all]/route.ts):
Client-side helpers (e.g. lib/auth-client.ts):
JWT retrieval:
Route protection:
Create a single auth configuration module (e.g. lib/auth.ts) that:
createAuth(...) from Better Auth with:
BETTER_AUTH_SECRET).Mount the auth handler in an API route such as:
app/api/auth/[...all]/route.ts using Better Auth’s Next.js
handler utilities.Do not duplicate auth configuration in multiple files.
Enable the JWT plugin in the Better Auth configuration when a separate backend (e.g. FastAPI) needs to verify users.
Use the plugin-provided endpoints or helpers to:
Keep JWT-specific logic in a dedicated module (e.g. lib/auth-jwt.ts):
Never hard-code JWT secrets in source files; always read them from environment variables.
Combine this Skill with the API client patterns Skill:
getAuthToken that
retrieves the JWT from a trusted source (session, cookies, Better
Auth helper).Rules for attaching the token:
Authorization header with Bearer <token> format unless
the backend explicitly requires something else.createApiClient
configuration), not in every component.The backend (e.g. FastAPI) is responsible for verifying the token using the same secret or JWKS that Better Auth uses.
For protected routes:
For server components / server actions:
For client components:
Always read the Better Auth secret and URLs from environment variables, for example:
BETTER_AUTH_SECRETBETTER_AUTH_URL or equivalent base URL for the auth handler.Never log secrets or tokens.
Document required environment variables in the project README, not in the Skill.
When present, this Skill should align with these conventions:
@/lib/auth.ts – Better Auth server-side configuration.@/lib/auth-client.ts – Client-side helpers for login/signup/logout.@/lib/auth-jwt.ts – Helpers to obtain JWT tokens from Better Auth.@/lib/api.ts – Shared API client that attaches the JWT token.app/api/auth/[...all]/route.ts – Auth route that mounts Better Auth.If any of these files are missing, propose creating them following Better Auth’s official Next.js integration guides and the patterns described above, instead of inventing a completely new auth flow.