better-auth-setup
1
总安装量
1
周安装量
#77058
全站排名
安装命令
npx skills add https://github.com/yigit433/nextjs-skills --skill better-auth-setup
Agent 安装分布
amp
1
opencode
1
kimi-cli
1
codex
1
github-copilot
1
claude-code
1
Skill 文档
better-auth-setup
Amaç
Better Auth kütüphanesini mevcut Next.js + Prisma projesine entegre eder. Email/password authentication, session yönetimi ve opsiyonel OAuth provider desteÄi sunar.
Ne Zaman Kullanılır
- Projeye authentication eklenecekse.
- Better Auth tercih ediliyorsa (lightweight, framework-agnostic, Prisma adapter desteÄi).
- Session-based auth stratejisi isteniyorsa.
Ãn KoÅullar
nextjs-bun-prisma-stackskill’i uygulanmıŠolmalı (veya eÅdeÄer bir Next.js + Prisma projesi mevcut).- PostgreSQL çalıÅır durumda.
Auth Stratejisi Kararı
Session-based auth tercih ediliyor:
- Revoke kolaylıÄı â JWT’de token süresi dolana kadar iptal zor, session anında silinebilir.
- Better Auth varsayılanı â Kütüphanenin birincil ve en iyi test edilmiÅ yolu.
- Server component uyumu â Next.js App Router’da server component’lerden session’a eriÅmek doÄal.
Adımlar
1. Paketleri kur
bun add better-auth
2. Auth config oluÅtur â src/lib/auth.ts
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { prisma } from "./prisma";
export const auth = betterAuth({
database: prismaAdapter(prisma, {
provider: "postgresql",
}),
emailAndPassword: {
enabled: true,
},
session: {
expiresIn: 60 * 60 * 24 * 7, // 7 gün
updateAge: 60 * 60 * 24, // 1 günde bir yenile
},
});
3. Auth client oluÅtur â src/lib/auth-client.ts
import { createAuthClient } from "better-auth/react";
export const authClient = createAuthClient({
baseURL: process.env.NEXT_PUBLIC_APP_URL,
});
export const {
signIn,
signUp,
signOut,
useSession,
} = authClient;
4. API route handler â src/app/api/auth/[...all]/route.ts
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";
export const { GET, POST } = toNextJsHandler(auth);
5. Prisma schema’ya auth tablolarını ekle
Better Auth CLI ile schema’yı generate et:
bunx @better-auth/cli generate --output ./prisma/schema.prisma
Veya tabloları manuel ekle (prisma/schema.prisma):
model User {
id String @id @default(cuid())
name String
email String @unique
emailVerified Boolean @default(false)
image String?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
sessions Session[]
accounts Account[]
@@map("users")
}
model Session {
id String @id @default(cuid())
expiresAt DateTime @map("expires_at")
token String @unique
ipAddress String? @map("ip_address")
userAgent String? @map("user_agent")
userId String @map("user_id")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("sessions")
}
model Account {
id String @id @default(cuid())
accountId String @map("account_id")
providerId String @map("provider_id")
userId String @map("user_id")
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
accessToken String? @map("access_token")
refreshToken String? @map("refresh_token")
idToken String? @map("id_token")
accessTokenExpiresAt DateTime? @map("access_token_expires_at")
refreshTokenExpiresAt DateTime? @map("refresh_token_expires_at")
scope String?
password String?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("accounts")
}
model Verification {
id String @id @default(cuid())
identifier String
value String
expiresAt DateTime @map("expires_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@map("verifications")
}
Migration çalıÅtır:
bunx prisma migrate dev --name add-auth-tables
6. Middleware â src/middleware.ts
import { auth } from "@/lib/auth";
import { headers } from "next/headers";
import { NextRequest, NextResponse } from "next/server";
const protectedRoutes = ["/dashboard"];
const authRoutes = ["/sign-in", "/sign-up"];
export async function middleware(request: NextRequest) {
const session = await auth.api.getSession({
headers: await headers(),
});
const { pathname } = request.nextUrl;
// Korumalı route â session yoksa sign-in'e yönlendir
if (protectedRoutes.some((route) => pathname.startsWith(route))) {
if (!session) {
return NextResponse.redirect(new URL("/sign-in", request.url));
}
}
// Auth route â session varsa dashboard'a yönlendir
if (authRoutes.some((route) => pathname.startsWith(route))) {
if (session) {
return NextResponse.redirect(new URL("/dashboard", request.url));
}
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*", "/sign-in", "/sign-up"],
};
7. Ortam deÄiÅkenleri
.env dosyasına ekle:
BETTER_AUTH_SECRET=generate_a_random_secret_here
BETTER_AUTH_URL=http://localhost:3000
Secret üretmek için:
openssl rand -base64 32
8. DoÄrulama
bunx prisma migrate dev # Auth tabloları oluÅtu mu?
bun dev # Proje hatasız çalıÅıyor mu?
curl -s http://localhost:3000/api/auth/ok # Auth endpoint yanıt veriyor mu?
DoD (Definition of Done)
- Email/password ile kayıt ve giriŠçalıÅıyor.
- Session oluÅturuluyor ve doÄrulanıyor.
- Korumalı route’lara yetkisiz eriÅim engellenmiÅ.
- Prisma migration auth tabloları için baÅarılı.
-
BETTER_AUTH_SECRET.env.example‘da placeholder olarak mevcut.