Skip to content
better-auth-ts logo

Better Auth TypeScript Skill

better-auth-ts

Better Auth TypeScript/JavaScript authentication library. Use when implementing auth in Next.js, React, Express, or any TypeScript project. Covers email/password, OAuth, JWT, sessions, 2FA, magic links, social login with Next.js 16 proxy.ts patterns.

SKILL.md

Full skill instructions

Better Auth TypeScript Skill

Better Auth is a framework-agnostic authentication and authorization library for TypeScript.

Quick Start

Installation

# npm
npm install better-auth

# pnpm
pnpm add better-auth

# yarn
yarn add better-auth

# bun
bun add better-auth

Basic Setup

See templates/​auth-server.ts for a complete template.

// lib/​auth.ts
import { betterAuth } from "better-auth";

export const auth = betterAuth({
  database: yourDatabaseAdapter, // See ORM guides below
  emailAndPassword: { enabled: true },
});
// lib/​auth-client.ts
import { createAuthClient } from "better-auth/​client";

export const authClient = createAuthClient({
  baseURL: process.env.NEXT_PUBLIC_APP_URL,
});

ORM Integration (Choose One)

IMPORTANT: Always use CLI to generate/​migrate schema:

npx @better-auth/​cli generate  # See current schema
npx @better-auth/​cli migrate   # Create/​update tables
ORMGuide
Drizzlereference/​drizzle.md
Prismareference/​prisma.md
Kyselyreference/​kysely.md
MongoDBreference/​mongodb.md
Direct DBUse pg Pool directly (see templates)

Next.js 16 Integration

API Route

// app/​api/​auth/[...all]/​route.ts
import { auth } from "@/​lib/​auth";
import { toNextJsHandler } from "better-auth/​next-js";

export const { GET, POST } = toNextJsHandler(auth.handler);

Proxy (Replaces Middleware)

In Next.js 16, middleware.ts → proxy.ts:

// proxy.ts
import { NextRequest, NextResponse } from "next/​server";
import { auth } from "@/​lib/​auth";
import { headers } from "next/​headers";

export async function proxy(request: NextRequest) {
  const session = await auth.api.getSession({
    headers: await headers(),
  });

  if (!session) {
    return NextResponse.redirect(new URL("/​sign-in", request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/​dashboard/:path*"],
};

Migration: npx @next/​codemod@canary middleware-to-proxy .

Server Component

import { auth } from "@/​lib/​auth";
import { headers } from "next/​headers";
import { redirect } from "next/​navigation";

export default async function DashboardPage() {
  const session = await auth.api.getSession({
    headers: await headers(),
  });

  if (!session) redirect("/​sign-in");

  return <h1>Welcome {session.user.name}</​h1>;
}

Authentication Examples

Quick Examples

Sign In

const { data, error } = await authClient.signIn.email({
  email: "[email protected]",
  password: "password",
});

Social OAuth

await authClient.signIn.social({
  provider: "google",
  callbackURL: "/​dashboard",
});

Sign Out

await authClient.signOut();

Get Session

const session = await authClient.getSession();

Plugins

import { twoFactor, magicLink, jwt, organization } from "better-auth/​plugins";

export const auth = betterAuth({
  plugins: [
    twoFactor(),
    magicLink({ sendMagicLink: async ({ email, url }) => { /​* send email */ } }),
    jwt(),
    organization(),
  ],
});

After adding plugins, always run:

npx @better-auth/​cli migrate

Advanced Patterns

See reference/​advanced-patterns.md for:

  • Stateless mode (no database)
  • Redis session storage
  • Custom user fields
  • Rate limiting
  • Organization hooks
  • SSO configuration
  • Multi-tenant setup

Templates

TemplatePurpose
templates/​auth-server.tsServer configuration template
templates/​auth-client.tsClient configuration template

Environment Variables

DATABASE_URL=postgresql://user:pass@host:5432/​db
NEXT_PUBLIC_APP_URL=http://localhost:3000
BETTER_AUTH_URL=http://localhost:3000
BETTER_AUTH_SECRET=your-secret

# OAuth (as needed)
GOOGLE_CLIENT_ID=...
GOOGLE_CLIENT_SECRET=...
GITHUB_CLIENT_ID=...
GITHUB_CLIENT_SECRET=...

Error Handling

// Client
const { data, error } = await authClient.signIn.email({ email, password });
if (error) {
  console.error(error.message, error.status);
}

// Server
import { APIError } from "better-auth/​api";
try {
  await auth.api.signInEmail({ body: { email, password } });
} catch (error) {
  if (error instanceof APIError) {
    console.log(error.message, error.status);
  }
}

Key Commands

# Generate schema
npx @better-auth/​cli generate

# Migrate database
npx @better-auth/​cli migrate

# Next.js 16 middleware migration
npx @next/​codemod@canary middleware-to-proxy .

Version Info

Always check latest docs before implementation - APIs may change between versions.

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View