Authentication
RocketFuel uses Better Auth for authentication. This guide covers configuration, customization, and common patterns.
Overview
When you enable authentication during rocketfuel init, you get:
- User registration and login pages
- Session management with secure cookies
- Database tables for users and sessions
- API routes at
/api/auth/*
Configuration
The auth configuration is in src/lib/auth.ts:
import { betterAuth } from "better-auth";import { drizzleAdapter } from "better-auth/adapters/drizzle";import { db } from "@/server/db";
export const auth = betterAuth({ database: drizzleAdapter(db, { provider: "pg", }), emailAndPassword: { enabled: true, },});Protecting Routes
Server Components
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("/login"); }
return <div>Welcome, {session.user.name}!</div>;}API Routes
import { auth } from "@/lib/auth";import { headers } from "next/headers";import { NextResponse } from "next/server";
export async function GET() { const session = await auth.api.getSession({ headers: await headers(), });
if (!session) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); }
return NextResponse.json({ user: session.user });}Client-Side Auth
Use the auth client for client-side operations:
"use client";
import { authClient } from "@/lib/auth-client";
export function LoginForm() { const handleLogin = async (email: string, password: string) => { await authClient.signIn.email({ email, password, }); };
const handleLogout = async () => { await authClient.signOut(); };
// ...}Customization
Adding OAuth Providers
import { betterAuth } from "better-auth";
export const auth = betterAuth({ // ... existing config socialProviders: { github: { clientId: process.env.GITHUB_CLIENT_ID!, clientSecret: process.env.GITHUB_CLIENT_SECRET!, }, google: { clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET!, }, },});Custom User Fields
Extend the user schema in src/server/db/schema.ts:
export const user = pgTable("user", { // ... existing fields role: text("role").default("user"), plan: text("plan").default("free"),});