Authentication
User authentication with Better-Auth
Overview
This project uses Better-Auth for authentication with support for email/password and OAuth providers.
Architecture
src/lib/auth/
├── server.ts # Server-side auth instance + layout guards
├── client.ts # Client-side auth hooks (useAuth)
├── definition.ts # Type definitions
└── permissions.ts # Permission utilities
src/features/auth/
├── schema.ts # User schemas and types
├── functions.ts # User database operations
├── hooks.ts # Auth-related form hooks
└── components/ # Auth UI componentsQuick Start
Server-Side
import { getAuth } from "@/lib/auth/server";
// Get current session
const auth = await getAuth();
if (auth?.user) {
console.log("Logged in as:", auth.user.email);
}Client-Side
"use client";
import { useAuth } from "@/lib/auth/client";
export function UserProfile() {
const { user, isAuthenticated, signOut } = useAuth();
if (!isAuthenticated) return <LoginPrompt />;
return (
<div>
Welcome, {user.name}
<button onClick={() => signOut()}>Logout</button>
</div>
);
}Authentication Flows
Email/Password Login
- User submits email/password
- Server validates credentials
- Session created and cookie set
- Redirect to callback URL or dashboard
OAuth Login
- User clicks provider button
- Redirect to provider's OAuth page
- User authorizes application
- Callback receives auth code
- Server exchanges code for tokens
- User account created/linked
- Session created and redirect
Email Verification
- User registers with email
- Verification email sent
- User clicks verification link
- Account marked as verified
- User can now fully access the app
Password Reset
- User requests password reset
- Reset email sent with token
- User clicks reset link
- User enters new password
- Password updated, session created
Auth Components
Login Form
import { FormLogin } from "@/features/auth/components";
<FormLogin
onSuccess={() => router.push(PageDashboard())}
showSocialProviders={true}
/>Register Form
import { FormRegister } from "@/features/auth/components";
<FormRegister onSuccess={() => router.push(PageLogin())} />User Dropdown
import { UserDropdown } from "@/features/auth/components";
<UserDropdown /> // Shows user menu or login buttonProtected Routes
Routes defined in PagesRequiringAuth are automatically protected:
// src/routes/routing.ts
PagesRequiringAuth: () => [
PageSettingsProfile,
PageDashboard,
PageAdmin,
],