Overview
Use Better Auth for session management and authentication. The auth() function validates sessions, and withAuth() wraps route handlers for protected endpoints.
What it is
Better Auth integration with session validation utilities and OAuth provider support for Google and GitHub.
Why we use it
Secure session management, OAuth integration, and consistent authentication patterns across all protected routes.
When to use
Any endpoint that requires user authentication. Use auth() to check sessions, withAuth() to wrap handlers.
Key Features
- auth() for session validation in routes
- withAuth() wrapper for protected handlers
- OAuth support (Google, GitHub)
- Secure token handling and storage
Quick Start
Check Authentication
Basic session validation in an API route.
// Check authentication in an API route
import { auth } from '@/lib/middleware/auth';
import { AuthenticationError } from '@/lib/errors';
export async function GET(request: Request) {
const session = await auth();
if (!session) {
throw new AuthenticationError('Authentication required');
}
// session.user is now available
const userId = session.user.id;
return NextResponse.json({ ok: true, data: { userId } });
}Patterns
Session Validation
Check authentication and access user data.
// Session validation pattern
import { auth } from '@/lib/middleware/auth';
export async function GET(request: Request) {
const session = await auth();
if (!session?.user) {
return NextResponse.json(
{ ok: false, error: { code: 'UNAUTHORIZED', message: 'Please log in' } },
{ status: 401 }
);
}
// Access user data
const { id, email, name } = session.user;
// ...
}withAuth Wrapper
Wrap handlers for guaranteed session.
// Using withAuth wrapper
import { withAuth } from '@/lib/middleware/auth';
export const GET = withAuth(async (request, session) => {
// session is guaranteed to exist
const userId = session.user.id;
const data = await getUserData(userId);
return NextResponse.json({ ok: true, data });
});OAuth Providers
Configure and use OAuth login.
// OAuth provider configuration
// Configured in @/lib/middleware/auth.ts
// Available providers:
// - Google OAuth
// - GitHub OAuth
// - Email/password (with verification)
// Login redirect example
import { signIn } from '@/lib/middleware/auth';
// In server action or API route
await signIn('google', { redirectTo: '/dashboard' });
await signIn('github', { redirectTo: '/dashboard' });Watch Out
Missing authentication checks on protected endpoints
Don't
// Missing authentication check
export async function GET(request: Request) {
const userId = request.headers.get('x-user-id');
const data = await getUserData(userId); // Dangerous!
return NextResponse.json({ ok: true, data });
}Do
// Proper authentication check
export async function GET(request: Request) {
const session = await auth();
if (!session) {
throw new AuthenticationError('Authentication required');
}
const data = await getUserData(session.user.id);
return NextResponse.json({ ok: true, data });
}Session fixation vulnerabilities
Don't
// Session fixation vulnerability
export async function POST(request: Request) {
const { userId } = await request.json();
// Setting session based on user input!
await setSession({ userId }); // Never do this!
}Do
// Proper session creation (via auth library)
// Better Auth handles session creation securely
// Never manually set session data from user input
import { signIn } from '@/lib/middleware/auth';
// Let the auth library validate credentials
const result = await signIn('credentials', {
email,
password,
redirect: false,
});- Storing sensitive data in session
- Exposing tokens in client-side code