Add Better Auth to a Next.js App Router project with API route handlers, database-backed sessions, client helpers, protected route checks, and production auth safety review.
The download URL is Better Auth's external source archive, not a HeyClaude-packaged skill archive; review source provenance before using it in automated workflows., Do not commit Better Auth secrets, OAuth provider secrets, database URLs, email-provider credentials, API-key plugin secrets, or copied dashboard values., Run schema generation or migrations only against the intended database environment; auth tables, sessions, accounts, and verification records are production-critical., Treat route protection as server-side authorization work. UI hiding, optimistic middleware redirects, or cookie existence checks are not full access control., Review `proxy.ts` or `middleware.ts` behavior by Next.js version before relying on database-backed session checks inside request middleware., Keep OAuth callback URLs, base URLs, trusted origins, and cookie settings environment-specific to avoid broken login loops or cross-environment session confusion., Track Better Auth release notes and security advisories before introducing auth flows or enabling advanced plugins in production., Add rollback steps before replacing an existing auth provider because user, account, session, and verification tables can affect active logins.
Privacy notes
Better Auth handles user identity, email addresses, password-auth state, OAuth profile data, sessions, cookies, accounts, verification tokens, and plugin-specific user data., Application logs, error trackers, request traces, AI prompts, and screenshots can retain user IDs, emails, callback URLs, cookies, session state, or OAuth provider details., Use synthetic users and test OAuth applications for examples, demos, issue reports, screenshots, and AI-assisted troubleshooting., If organization, API key, two-factor, passkey, or SSO plugins are enabled, treat membership, roles, credentials, and device metadata as sensitive authorization data., Review Better Auth, database, deployment-provider, analytics, email-provider, and AI-assistant retention policies before using real customer identity data.
8 safety and 5 privacy notes across 5 risk areas. Review closely: credentials & tokens, permissions & scopes, network access, third-party handling.
5 areas
SafetyNetwork accessThe download URL is Better Auth's external source archive, not a HeyClaude-packaged skill archive; review source provenance before using it in automated workflows.
SafetyCredentials & tokensRun schema generation or migrations only against the intended database environment; auth tables, sessions, accounts, and verification records are production-critical.
SafetyPermissions & scopesTreat route protection as server-side authorization work. UI hiding, optimistic middleware redirects, or cookie existence checks are not full access control.
SafetyCredentials & tokensReview `proxy.ts` or `middleware.ts` behavior by Next.js version before relying on database-backed session checks inside request middleware.
SafetyCredentials & tokensKeep OAuth callback URLs, base URLs, trusted origins, and cookie settings environment-specific to avoid broken login loops or cross-environment session confusion.
SafetyGeneralTrack Better Auth release notes and security advisories before introducing auth flows or enabling advanced plugins in production.
SafetyCredentials & tokensAdd rollback steps before replacing an existing auth provider because user, account, session, and verification tables can affect active logins.
PrivacyCredentials & tokensBetter Auth handles user identity, email addresses, password-auth state, OAuth profile data, sessions, cookies, accounts, verification tokens, and plugin-specific user data.
PrivacyCredentials & tokensApplication logs, error trackers, request traces, AI prompts, and screenshots can retain user IDs, emails, callback URLs, cookies, session state, or OAuth provider details.
PrivacyCredentials & tokensUse synthetic users and test OAuth applications for examples, demos, issue reports, screenshots, and AI-assisted troubleshooting.
PrivacyCredentials & tokensIf organization, API key, two-factor, passkey, or SSO plugins are enabled, treat membership, roles, credentials, and device metadata as sensitive authorization data.
PrivacyThird-party handlingReview Better Auth, database, deployment-provider, analytics, email-provider, and AI-assistant retention policies before using real customer identity data.
Safety notes
The download URL is Better Auth's external source archive, not a HeyClaude-packaged skill archive; review source provenance before using it in automated workflows.
Do not commit Better Auth secrets, OAuth provider secrets, database URLs, email-provider credentials, API-key plugin secrets, or copied dashboard values.
Run schema generation or migrations only against the intended database environment; auth tables, sessions, accounts, and verification records are production-critical.
Treat route protection as server-side authorization work. UI hiding, optimistic middleware redirects, or cookie existence checks are not full access control.
Review `proxy.ts` or `middleware.ts` behavior by Next.js version before relying on database-backed session checks inside request middleware.
Keep OAuth callback URLs, base URLs, trusted origins, and cookie settings environment-specific to avoid broken login loops or cross-environment session confusion.
Track Better Auth release notes and security advisories before introducing auth flows or enabling advanced plugins in production.
Add rollback steps before replacing an existing auth provider because user, account, session, and verification tables can affect active logins.
Privacy notes
Better Auth handles user identity, email addresses, password-auth state, OAuth profile data, sessions, cookies, accounts, verification tokens, and plugin-specific user data.
Application logs, error trackers, request traces, AI prompts, and screenshots can retain user IDs, emails, callback URLs, cookies, session state, or OAuth provider details.
Use synthetic users and test OAuth applications for examples, demos, issue reports, screenshots, and AI-assisted troubleshooting.
If organization, API key, two-factor, passkey, or SSO plugins are enabled, treat membership, roles, credentials, and device metadata as sensitive authorization data.
Review Better Auth, database, deployment-provider, analytics, email-provider, and AI-assistant retention policies before using real customer identity data.
Prerequisites
Next.js App Router project or migration branch with a known package manager.
Database choice and adapter plan, such as Drizzle, Prisma, MongoDB, or Better Auth's built-in Kysely-backed flow.
Local, preview, staging, and production secret-management path for Better Auth secrets, OAuth client IDs, and OAuth client secrets.
Route map that separates public pages, authenticated pages, API routes, server actions, admin routes, and organization-scoped areas.
Decision on email/password, social providers, passkeys, magic links, organization support, API keys, or other Better Auth plugins.
Production base URL, trusted origins, cookie domain, callback URL, and redirect URL plan.
.gemini/skills/<skill-name>/SKILL.md or .agents/skills/<skill-name>/SKILL.md
cursor
Adapter
.cursor/rules/<skill-name>.mdc
cli
Manual
AGENTS.md or tool-specific context file
Full copyable content
# Trigger
"Apply the Better Auth Next.js authentication skill to this app."
# Required output
1) Current auth, route, database, and cookie/session inventory
2) Better Auth package, env, adapter, route handler, and client plan
3) Protected route, server action, and API authorization checklist
4) Production safety, privacy, secret, and rollback notes
About this resource
Knowledge Freshness
This skill is based on Better Auth's official website, installation docs, Next.js
integration docs, and better-auth/better-auth repository reviewed on
2026-06-04. The current Next.js guide mounts Better Auth at
app/api/auth/[...all]/route.ts with toNextJsHandler(auth), creates a client
with createAuthClient() from better-auth/react, and documents server action
cookie handling, proxy.ts/middleware.ts route protection, and Next.js 16
proxy compatibility.
Prefer the live Better Auth docs and official repository over model memory for
package imports, route filenames, adapter examples, cookie helpers, plugin
names, migration commands, and Next.js runtime guidance.
Scope Note
Use this skill for Better Auth-backed authentication in a Next.js application.
It is not a generic authentication architecture guide, a replacement for threat
modeling, or a shortcut around product security review for finance, healthcare,
education, admin, enterprise identity, or high-risk multi-tenant systems.
Core Workflow
Inventory the current app structure, Next.js version, router mode, package
manager, /src usage, public pages, authenticated pages, API handlers,
server actions, admin routes, and organization boundaries.
Identify existing auth code, session stores, cookie names, middleware,
authorization helpers, user tables, OAuth callbacks, and environment
variables before adding Better Auth.
Confirm the target Better Auth feature set: email/password, social providers,
passkeys, magic links, organizations, API keys, two-factor authentication,
SSO, or other plugins.
Add better-auth with the project package manager and document the required
secret variables for local, preview, staging, and production environments.
Create the Better Auth server instance in a stable server-only module and
choose the database adapter deliberately instead of accepting an accidental
local-only default.
Generate or plan the required auth schema and migrations, then review the
target database before applying any migration that creates or changes user,
session, account, or verification tables.
Mount the API route handler at the documented catch-all route with
toNextJsHandler(auth) for App Router projects.
Add a typed auth client with createAuthClient() and keep client-side auth UI
separate from server-side authorization checks.
Handle server actions that set cookies with the documented Better Auth
Next.js helper path, keeping cookie behavior explicit in tests.
Protect routes and server actions from the route inventory. Do not assume a
cookie-only redirect is enough for data access or write operations.
Review OAuth provider settings, callback URLs, trusted origins, base URL,
cookie domain, HTTPS behavior, and deployment preview domains before merge.
Produce validation notes for sign-up, sign-in, sign-out, session refresh,
protected page access, protected API access, server action auth, OAuth
callback handling, and rollback.
Required Inputs
Next.js version, router mode, package manager, and whether the app uses a
/src directory.
Existing auth provider or custom auth implementation, including tables,
cookies, middleware, session helpers, and route guards.
Database provider, ORM or adapter, migration workflow, and target environment
for schema changes.
List of public, authenticated, admin, API, server action, organization, and
webhook routes.
Desired Better Auth methods and plugins, including email/password, social
sign-in, passkeys, magic links, organizations, API keys, 2FA, SSO, or
one-time tokens.
Local, preview, staging, and production values for base URL, trusted origins,
callback URLs, cookie domain, and secret management.
Deployment provider and rollback plan for restoring the previous auth flow if
production login breaks.
Production Rules
Keep Better Auth server configuration in server-only code. Do not expose
secrets, database URLs, OAuth client secrets, email-provider credentials, or
API-key plugin secrets to client bundles.
Treat the auth schema as critical application data. Review generated SQL or
ORM migrations before applying them, and back up production data before
replacing an existing auth provider.
Protect server actions, route handlers, tRPC procedures, loaders, background
jobs, webhooks, and direct database writes at the server boundary.
Use route middleware or proxy checks for redirects and fast rejection, but
keep full authorization checks near the protected data or mutation.
Test unauthenticated access to every protected page and API route. Include at
least one negative test where the UI is bypassed and the server endpoint is
called directly.
Keep OAuth callback URLs and trusted origins specific to each environment.
Preview domains should not silently reuse production credentials unless that
is an intentional and documented deployment decision.
Use synthetic users, test OAuth applications, and non-production email
providers for demos, screenshots, bug reports, and AI prompts.
Review Better Auth releases and security notes before enabling new plugins or
shipping auth changes to production.
Compatibility
Native
Claude Code / Claude: use as a reusable Agent Skill for authentication
planning, migration review, implementation guidance, and production auth
checklists.
Codex/OpenAI workflows: use as SKILL.md-style instructions when editing
Next.js apps or reviewing Better Auth changes.
Manual Adaptation
Cursor, Windsurf, Gemini, and Generic AGENTS files: adapt the trigger,
workflow, safety notes, privacy notes, and output contract into repository
rules for auth work.
Output Contract
Source evidence: Better Auth docs, website, and repository URLs reviewed,
with date.
App inventory: router, routes, existing auth code, database, cookies,
session helpers, API boundaries, and deployment environments.
Safety and privacy review: secrets, OAuth credentials, database migrations,
cookies, trusted origins, logs, prompts, and real-user data handling.
Validation checklist: sign-up, sign-in, sign-out, session read, protected
page, protected API route, server action auth, OAuth callback, preview
deploy, production smoke test, and rollback.
Duplicate And Source Review
Current HeyClaude content mentions Better Auth inside generic agent, command,
and Windsurf collaboration examples, but there is no dedicated Better Auth,
better-auth, toNextJsHandler, or better-auth/better-auth content entry.
This skill is specifically scoped to the official Better Auth Next.js workflow
and is source-backed by the current Better Auth docs and repository.
Troubleshooting
Issue: The API route returns 404 or the auth client cannot reach Better Auth
Fix: Confirm the catch-all route path matches the current router mode. For
App Router projects, the documented route is app/api/auth/[...all]/route.ts
with toNextJsHandler(auth).
Issue: Sign-in works locally but fails on preview or production
Fix: Check the environment-specific base URL, trusted origins, OAuth
callback URLs, HTTPS configuration, and cookie domain. Do not reuse local
callback assumptions for deployed environments.
Issue: A protected page redirects correctly, but a direct API call still
returns sensitive data
Fix: Add server-side session and authorization checks inside the API route,
server action, loader, tRPC procedure, or data-access layer. Redirect middleware
is not enough for write or data access protection.
Issue: Server actions sign users in but cookies are not persisted
Fix: Re-check Better Auth's current Next.js server action cookie guidance
and plugin ordering. Make cookie behavior part of the local validation checklist
instead of assuming the browser session was established.
Issue: Migration creates unexpected auth tables or columns
Fix: Stop before applying the migration to shared data. Review the adapter,
provider option, generated schema, target database URL, and rollback plan, then
rerun against a disposable database first.
Show that Better Auth Next.js Authentication Skill is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.
[](https://heyclau.de/entry/skills/better-auth-nextjs-authentication)
How it compares
Better Auth Next.js Authentication Skill side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.
Add Better Auth to a Next.js App Router project with API route handlers, database-backed sessions, client helpers, protected route checks, and production auth safety review.
Add Clerk authentication to a Next.js App Router project with middleware, route protection, session-aware UI, environment hygiene, and production auth safety checks.
Add or maintain next-intl internationalization in a Next.js App Router project with messages, request configuration, locale-based routing, proxy or middleware behavior, Server and Client Components, typed message keys, localized navigation, SEO review, testing, and rollout planning.
✓The download URL is Better Auth's external source archive, not a HeyClaude-packaged skill archive; review source provenance before using it in automated workflows.
Do not commit Better Auth secrets, OAuth provider secrets, database URLs, email-provider credentials, API-key plugin secrets, or copied dashboard values.
Run schema generation or migrations only against the intended database environment; auth tables, sessions, accounts, and verification records are production-critical.
Treat route protection as server-side authorization work. UI hiding, optimistic middleware redirects, or cookie existence checks are not full access control.
Review `proxy.ts` or `middleware.ts` behavior by Next.js version before relying on database-backed session checks inside request middleware.
Keep OAuth callback URLs, base URLs, trusted origins, and cookie settings environment-specific to avoid broken login loops or cross-environment session confusion.
Track Better Auth release notes and security advisories before introducing auth flows or enabling advanced plugins in production.
Add rollback steps before replacing an existing auth provider because user, account, session, and verification tables can affect active logins.
✓The download URL is Clerk's external JavaScript SDK source archive, not a HeyClaude-packaged skill archive; review source provenance before using it in automated workflows.
Clerk middleware does not protect routes by default; require an explicit protected-route matcher before assuming a page, API route, or tRPC endpoint is private.
Do not commit `CLERK_SECRET_KEY`, webhook signing secrets, OAuth provider secrets, or copied dashboard values to source control, issue comments, screenshots, or chat transcripts.
Review middleware matchers carefully. A broad matcher can affect static assets and public routes, while a narrow matcher can leave sensitive routes unauthenticated.
Treat organization roles, custom permissions, and metadata checks as authorization logic that needs tests, not just UI hiding.
Webhook handlers can mutate user, membership, subscription, and organization state. Make handlers idempotent and verify signatures before processing events.
Confirm production domains and redirect URLs before deploy; wrong origins can break sign-in, leak users into the wrong environment, or create confusing callback loops.
✓The download URL is Convex's external JavaScript SDK source archive, not a HeyClaude-packaged skill archive; review source provenance before using it in automated workflows.
`convex dev` logs in, creates or connects a cloud dev deployment, writes deployment URLs, and syncs backend functions; confirm the target account and project first.
Treat `convex import`, migrations, table rewrites, backfills, deletes, and scheduled functions as data-mutating operations that need environment confirmation.
Do not commit Convex deployment secrets, auth provider secrets, API keys for actions, webhook secrets, or copied dashboard values.
Keep client-exposed values such as `NEXT_PUBLIC_CONVEX_URL` separate from server-only secrets used by actions, auth providers, integrations, or external APIs.
Review generated APIs, table indexes, pagination, and query fan-out before shipping realtime screens that could overload clients or expose broad datasets.
When actions call external services or LLM APIs, add timeout, retry, logging, rate-limit, and secret-handling guidance before production use.
✓The download URL is the external `amannn/next-intl` source archive, not a HeyClaude-packaged skill archive; review source provenance before using it in automated workflows.
Locale routing can change public URLs, redirects, cache keys, static rendering behavior, metadata, sitemap output, canonical URLs, and analytics attribution.
Proxy or middleware rules can run for broad request sets. Review matchers, excluded assets, API routes, auth routes, preview mode, and static files before shipping.
Do not put secrets, unreleased product copy, private customer examples, support transcripts, or regulated data into translation messages, examples, screenshots, or AI prompts.
AI-assisted translation output needs human review for product accuracy, legal terms, accessibility labels, cultural fit, pluralization, and formatting placeholders.
TypeScript message-key augmentation can expose missing keys and route type errors at build time. Treat new type failures as content or routing defects, not noise to suppress.
Static rendering with locale params can affect build size, revalidation, and deployment time. Review generated paths, `generateStaticParams`, and fallback strategy before broad locale rollout.
Locale switchers and redirects can lock users into the wrong locale or loop if cookies, domains, prefixes, and auth redirects are not tested together.
Privacy notes
✓Better Auth handles user identity, email addresses, password-auth state, OAuth profile data, sessions, cookies, accounts, verification tokens, and plugin-specific user data.
Application logs, error trackers, request traces, AI prompts, and screenshots can retain user IDs, emails, callback URLs, cookies, session state, or OAuth provider details.
Use synthetic users and test OAuth applications for examples, demos, issue reports, screenshots, and AI-assisted troubleshooting.
If organization, API key, two-factor, passkey, or SSO plugins are enabled, treat membership, roles, credentials, and device metadata as sensitive authorization data.
Review Better Auth, database, deployment-provider, analytics, email-provider, and AI-assistant retention policies before using real customer identity data.
✓Clerk processes user identity, email addresses, sessions, cookies, authentication factors, OAuth profile data, organization membership, and optional user metadata.
Application logs, error reports, webhook payloads, request traces, and AI chat transcripts can retain user IDs, email addresses, session state, redirect URLs, or organization names.
Keep public examples synthetic. Do not paste real Clerk keys, dashboard screenshots, webhook payloads, user records, or organization metadata into prompts or PRs.
Review Clerk, deployment-provider, analytics, and AI-assistant retention policies before using real customer identity data in troubleshooting sessions.
If custom metadata stores roles, billing flags, internal account IDs, or entitlement data, treat it as sensitive authorization data and avoid exposing it client-side unless intended.
✓Convex can store user records, app data, realtime query results, auth identifiers, scheduled job state, file metadata, logs, and action inputs or outputs.
Client queries, browser traces, app logs, error trackers, screenshots, and AI prompts can expose document IDs, user IDs, table names, deployment URLs, or sampled records.
Use synthetic seed data for examples, imports, demos, issue reports, screenshots, and AI-assisted troubleshooting.
Review Convex, auth-provider, deployment-provider, analytics, external API, and AI-assistant retention policies before using real customer data.
If Convex actions call LLMs, payment systems, email providers, or webhooks, document what user data leaves Convex and where it is retained.
✓next-intl projects can process locale preferences, route locale params, locale cookies, Accept-Language headers, localized content, user-facing copy, CMS payloads, and analytics events.
Translation files, CMS exports, screenshots, prompts, pull requests, and issue reports can reveal unreleased messaging, pricing, product plans, legal text, user examples, or internal route names.
Locale detection, domain routing, redirects, and analytics can combine language preference with IP-derived geography, logged-in user identifiers, or marketing attribution.
Use synthetic content, placeholder brands, redacted examples, and non-production locales for demos, screenshots, validation, and AI-assisted troubleshooting.
Review Next.js, next-intl, translation-management, CMS, analytics, logging, hosting, and AI-assistant retention behavior before using real customer content or support text in localization workflows.
Prerequisites
Next.js App Router project or migration branch with a known package manager.
Database choice and adapter plan, such as Drizzle, Prisma, MongoDB, or Better Auth's built-in Kysely-backed flow.
Local, preview, staging, and production secret-management path for Better Auth secrets, OAuth client IDs, and OAuth client secrets.
Route map that separates public pages, authenticated pages, API routes, server actions, admin routes, and organization-scoped areas.
Next.js App Router project or migration branch.
Clerk account and application for the target environment.
`NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` and `CLERK_SECRET_KEY` available through local and deployment environment configuration.
Route map that separates public pages, protected app pages, API routes, and admin or organization-scoped areas.
Next.js App Router project or migration branch with a known package manager.
Convex account access and permission to create or use the target Convex project and deployment.
`NEXT_PUBLIC_CONVEX_URL` and any Convex deployment environment variables managed through local, preview, staging, and production secret configuration.
Data model plan for Convex tables, indexes, generated API functions, and client query/mutation usage.
Next.js project with App Router, Pages Router, or a known migration plan; App Router should be identified explicitly before applying current next-intl setup guidance.
Locale strategy covering supported locales, default locale, locale prefixes, domain routing, fallback behavior, and whether routes should use a top-level `[locale]` segment.
Message source plan covering local JSON files, remote CMS or translation management system, namespace structure, review workflow, and missing-key behavior.
Decision for where `i18n/request.ts`, routing config, navigation helpers, and proxy or middleware files belong in the repository layout.