Authentication
How authentication works in KitAI.
Overview
KitAI uses Better Auth and supports multiple sign-in methods.
Supported methods
Google OAuth
- Go to Google Cloud Console
- Create an OAuth 2.0 Client ID
- Set the authorized redirect URI to
http://localhost:3000/api/auth/callback/google - Add credentials to
.env.local:
GOOGLE_CLIENT_ID=your_client_id
GOOGLE_CLIENT_SECRET=your_client_secretGitHub OAuth
- Go to GitHub Developer Settings
- Create a new OAuth app
- Set the callback URL to
http://localhost:3000/api/auth/callback/github - Add credentials to
.env.local:
GITHUB_CLIENT_ID=your_client_id
GITHUB_CLIENT_SECRET=your_client_secretMagic Link (email)
Use Resend for email delivery:
RESEND_API_KEY=your_resend_api_key
EMAIL_FROM=noreply@yourdomain.comSession management
Better Auth uses secure, httpOnly cookies:
- Default session length: 7 days
- Automatic refresh: every 24 hours
Protecting routes
// src/middleware.ts
export async function middleware(request: NextRequest) {
const session = await auth.api.getSession({
headers: request.headers,
});
if (!session?.user) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}Client-side usage
'use client';
import { useSession, signOut } from '@/lib/auth/client';
export function UserProfile() {
const { data: session } = useSession();
if (!session?.user) {
return <div>Not signed in</div>;
}
return (
<div>
<p>Welcome, {session.user.name}</p>
<button onClick={() => signOut()}>Sign out</button>
</div>
);
}Server-side usage
import { auth } from '@/lib/auth';
import { headers } from 'next/headers';
export async function GET() {
const headersList = await headers();
const session = await auth.api.getSession({ headers: headersList });
if (!session?.user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
return NextResponse.json({ user: session.user });
}Roles
KitAI supports two roles:
useradmin
Admins can access /admin.