/jezweb:better-authfrom jezweb
Provides Better Auth authentication integration patterns for NestJS backend and Next.js frontend with Drizzle ORM and PostgreSQL. Use when implementing authentication - Setting up Better Auth with NestJS backend, Integrating Next.js App Router frontend, Configuring Drizzle ORM schema with PostgreSQL, Implementing social login (GitHub, Google, etc.), Adding plugins (2FA, Organization, SSO, Magic Link, Passkey), Email/password authentication with session management, Creating protected routes and middleware
Ships in jezweb. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Better Auth is a comprehensive authentication framework for TypeScript that provides type-safe authentication with support for multiple providers, 2FA, SSO, organizations, and more. This skill covers complete integration patterns for NestJS backend with Drizzle ORM and PostgreSQL, plus Next.js App Router frontend integration.
# Backend (NestJS)
npm install better-auth @auth/drizzle-adapter
npm install drizzle-orm pg
npm install -D drizzle-kit
# Frontend (Next.js)
npm install better-auth
See References/ for detailed setup instructions.
src/
├── auth/
│ ├── auth.module.ts # Auth module configuration
│ ├── auth.controller.ts # Auth HTTP endpoints
│ ├── auth.service.ts # Business logic
│ ├── auth.guard.ts # Route protection
│ └── schema.ts # Drizzle auth schema
├── database/
│ ├── database.module.ts # Database module
│ └── database.service.ts # Drizzle connection
└── main.ts
app/
├── (auth)/
│ ├── sign-in/
│ │ └── page.tsx # Sign in page
│ └── sign-up/
│ └── page.tsx # Sign up page
├── (dashboard)/
│ ├── dashboard/
│ │ └── page.tsx # Protected page
│ └── layout.tsx # With auth check
├── api/
│ └── auth/
│ └── [...auth]/route.ts # Auth API route
├── layout.tsx # Root layout
└── middleware.ts # Auth middleware
lib/
├── auth.ts # Better Auth client
└── utils.ts
Install Dependencies
npm install drizzle-orm pg @auth/drizzle-adapter better-auth
npm install -D drizzle-kit
Configure Drizzle
drizzle.config.tsGenerate and Run Migrations
npx drizzle-kit generate
npx drizzle-kit migrate
Create Database Module
Configure Better Auth
Create Auth Module
Configure Auth Client
Create Auth Pages
Add Middleware
Social Providers
Plugins
Input: Developer needs to set up Better Auth in a new NestJS project with PostgreSQL.
Process:
// 1. Create auth instance
export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: "pg",
schema: { ...schema }
}),
socialProviders: {
github: {
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
}
}
});
// 2. Create auth controller
@Controller('auth')
export class AuthController {
@All('*')
async handleAuth(@Req() req: Request, @Res() res: Response) {
return auth.handler(req);
}
}
Output: Fully functional auth endpoints at /auth/* with GitHub OAuth support.
Input: Protect dashboard routes in Next.js App Router.
Process:
// middleware.ts
import { auth } from '@/lib/auth';
export default auth((req) => {
if (!req.auth && req.nextUrl.pathname.startsWith('/dashboard')) {
const newUrl = new URL('/sign-in', req.nextUrl.origin);
return Response.redirect(newUrl);
}
});
export const config = {
matcher: ['/dashboard/:path*', '/api/protected/:path*']
};
Output: Unauthenticated users are redirected to /sign-in when accessing /dashboard/*.
Input: Display user data in a Next.js Server Component.
Process:
// app/dashboard/page.tsx
import { auth } from '@/lib/auth';
import { redirect } from 'next/navigation';
export default async function DashboardPage() {
const session = await auth();
if (!session) {
redirect('/sign-in');
}
return (
<div>
<h1>Welcome, {session.user.name}</h1>
<p>Email: {session.user.email}</p>
</div>
);
}
Output: Renders user information only for authenticated users, redirects others to sign-in.
Input: Enable 2FA for enhanced account security.
Process:
// Enable 2FA plugin
export const auth = betterAuth({
plugins: [
twoFactor({
issuer: 'MyApp',
otpOptions: {
digits: 6,
period: 30
}
})
]
});
// Client-side enable 2FA
const { data, error } = await authClient.twoFactor.enable({
password: 'user-password'
});
Output: Users can enable TOTP-based 2FA and verify with authenticator apps.
Input: User has enabled 2FA and wants to sign in, marking the device as trusted.
Process:
// Server-side: Configure 2FA with OTP sending
export const auth = betterAuth({
plugins: [
twoFactor({
issuer: 'MyApp',
otpOptions: {
async sendOTP({ user, otp }, ctx) {
// Send OTP via email, SMS, or other method
await sendEmail({
to: user.email,
subject: 'Your verification code',
body: `Code: ${otp}`
});
}
}
})
]
});
// Client-side: Verify TOTP and trust device
const verify2FA = async (code: string) => {
const { data, error } = await authClient.twoFactor.verifyTotp({
code,
trustDevice: true // Device trusted for 30 days
});
if (data) {
// Redirect to dashboard
router.push('/dashboard');
}
};
Output: User is authenticated, device is trusted for 30 days (no 2FA prompt on next sign-ins).
Input: Enable passkey (WebAuthn) authentication for passwordless login.
Process:
// Server-side: Configure passkey plugin
import { passkey } from '@better-auth/passkey';
export const auth = betterAuth({
plugins: [
passkey({
rpID: 'example.com', // Relying Party ID (your domain)
rpName: 'My App', // Display name
advanced: {
webAuthnChallengeCookie: 'my-app-passkey'
}
})
]
});
// Client-side: Register passkey
const registerPasskey = async () => {
const { data, error } = await authClient.passkey.register({
name: 'My Device'
});
if (data) {
console.log('Passkey registered successfully');
}
};
// Client-side: Sign in with passkey
const signInWithPasskey = async () => {
await authClient.signIn.passkey({
autoFill: true, // Enable conditional UI
fetchOptions: {
onSuccess() {
router.push('/dashboard');
}
}
});
};
Output: Users can register and authenticate with passkeys (biometric, PIN, or security key).
Input: Implement passkey autofill in sign-in form for seamless authentication.
Process:
// Component with conditional UI support
'use client';
import { useEffect } from 'react';
import { authClient } from '@/lib/auth/client';
export default function SignInPage() {
useEffect(() => {
// Check for conditional mediation support
if (!PublicKeyCredential.isConditionalMediationAvailable ||
!PublicKeyCredential.isConditionalMediationAvailable()) {
return;
}
// Enable passkey autofill
void authClient.signIn.passkey({ autoFill: true });
}, []);
return (
<form>
<label htmlFor="email">Email:</label>
<input
type="email"
name="email"
autoComplete="username webauthn"
/>
<label htmlFor="password">Password:</label>
<input
type="password"
name="password"
autoComplete="current-password webauthn"
/>
<button type="submit">Sign In</button>
</form>
);
}
Output: Browser automatically suggests passkeys when user focuses on input fields.
Input: User needs backup codes to recover account if authenticator app is lost.
Process:
// Enable 2FA - backup codes are generated automatically
const enable2FA = async (password: string) => {
const { data, error } = await authClient.twoFactor.enable({
password
});
if (data) {
// IMPORTANT: Display backup codes to user immediately
console.log('Backup codes (save these securely):');
data.backupCodes.forEach((code: string) => {
console.log(code);
});
// Show TOTP URI as QR code
const qrCodeUrl = data.totpURI;
displayQRCode(qrCodeUrl);
}
};
// Recover with backup code
const recoverWithBackupCode = async (code: string) => {
const { data, error } = await authClient.twoFactor.verifyBackupCode({
code
});
if (data) {
// Allow user to disable 2FA or set up new authenticator
router.push('/settings/2fa');
}
};
Output: User receives single-use backup codes for account recovery.
// NestJS Guard
@Controller('dashboard')
@UseGuards(AuthGuard)
export class DashboardController {
@Get()
getDashboard(@Request() req) {
return req.user;
}
}
// Next.js Server Component
import { auth } from '@/lib/auth';
import { redirect } from 'next/navigation';
export default async function Dashboard() {
const session = await auth();
if (!session) {
redirect('/sign-in');
}
return <div>Welcome {session.user.name}</div>;
}
// Get session in API route
const session = await auth.api.getSession({
headers: await headers()
});
// Get session in Server Component
const session = await auth();
// Get session in Client Component
'use client';
import { useSession } from '@/lib/auth/client';
const { data: session } = useSession();
Environment Variables: Always use environment variables for sensitive data (secrets, database URLs, OAuth credentials)
Secret Generation: Use strong, unique secrets for Better Auth. Generate with openssl rand -base64 32
HTTPS Required: OAuth callbacks require HTTPS in production. Use ngrok or similar for local testing
Session Security: Configure appropriate session expiration times based on your security requirements
Database Indexing: Add indexes on frequently queried fields (email, userId) for performance
Error Handling: Implement proper error handling for auth failures without revealing sensitive information
Rate Limiting: Add rate limiting to auth endpoints to prevent brute force attacks
CSRF Protection: Better Auth includes CSRF protection. Always use the provided methods for state changes
Type Safety: Leverage TypeScript types from Better Auth for full type safety across frontend and backend
Testing: Test auth flows thoroughly including success cases, error cases, and edge conditions
.env to .gitignore and never commit OAuth secrets or database credentials{
"dependencies": {
"better-auth": "^1.2.0",
"@auth/drizzle-adapter": "^1.0.0",
"drizzle-orm": "^0.35.0",
"pg": "^8.12.0",
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/config": "^3.0.0"
},
"devDependencies": {
"drizzle-kit": "^0.24.0",
"@types/pg": "^8.11.0"
}
}
{
"dependencies": {
"better-auth": "^1.2.0",
"next": "^15.0.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
}
}
Problem: Session data is not being persisted or retrieved correctly.
Solution:
BETTER_AUTH_SECRET is set consistentlyProblem: OAuth state mismatch during callback.
Solution:
BETTER_AUTH_URL is set correctly in environmentProblem: Type inference not working correctly.
Solution:
npx better-auth typegen to generate typesbetter-auth versions match on frontend and backendProblem: Drizzle migration conflicts.
Solution:
drizzle-kit push for developmentProblem: Frontend cannot communicate with backend auth endpoints.
Solution:
credentials: 'include'Problem: OAuth app configuration mismatch.
Solution:
references/nestjs-setup.md for complete NestJS setupreferences/nextjs-setup.md for complete Next.js setupreferences/plugins.md for plugin configurationassets/ for example code filesSee Assets/env.example for all required environment variables.
# Database
DATABASE_URL=postgresql://user:password@localhost:5432/dbname
# Better Auth
BETTER_AUTH_SECRET=your-secret-key-min-32-chars
BETTER_AUTH_URL=http://localhost:3000
# OAuth Providers
AUTH_GITHUB_CLIENT_ID=your-github-client-id
AUTH_GITHUB_CLIENT_SECRET=your-github-client-secret
AUTH_GOOGLE_CLIENT_ID=your-google-client-id
AUTH_GOOGLE_CLIENT_SECRET=your-google-client-secret
# Email (for magic links and verification)
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=your-smtp-user
SMTP_PASSWORD=your-smtp-password
[email protected]
# Session (optional, for Redis)
REDIS_URL=redis://localhost:6379
assets/env.example (opens in a new tab)assets/nestjs/auth.controller.ts (opens in a new tab)assets/nestjs/auth.guard.ts (opens in a new tab)assets/nestjs/auth.module.ts (opens in a new tab)assets/nestjs/auth.schema.ts (opens in a new tab)assets/nestjs/auth.service.ts (opens in a new tab)assets/nestjs/database.module.ts (opens in a new tab)assets/nestjs/database.service.ts (opens in a new tab)assets/nextjs/auth-client.ts (opens in a new tab)assets/nextjs/auth-route.ts (opens in a new tab)assets/nextjs/dashboard-page.tsx (opens in a new tab)assets/nextjs/middleware.ts (opens in a new tab)assets/nextjs/sign-in-page.tsx (opens in a new tab)assets/nextjs/use-session.ts (opens in a new tab)references/PLUGINS.md (opens in a new tab)references/SCHEMA.md (opens in a new tab)references/mfa-2fa.md (opens in a new tab)references/nestjs-setup.md (opens in a new tab)references/nextjs-setup.md (opens in a new tab)references/passkey.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub ulpi-io/plugin-marketplace --plugin jezweb100 skills in this plugin
/accessibilityAudit and improve web accessibility following WCAG 2.1 guidelines. Use when asked to "improve accessibility", "a11y audit", "WCAG compliance", "screen reader support", "keyboard navigation", or "make accessible"./agent-developmentThis skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins./ai-sdk-coretailwind-theme-builderOther plugins' skills for the same job
2 plugins in one repository ship this exact skill · first indexed Jul 18, 2026