Documentation

Authentication

Better-auth setup for web and mobile apps

Authentication

Better-auth handles authentication for both web and mobile apps.

Setup

Package: @repo/auth-utils

Dependencies:

  • better-auth 1.2.10
  • @better-auth/expo 1.2.10 (mobile)

Configuration

// packages/auth-utils/auth.ts
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";

export const auth = betterAuth({
  database: prismaAdapter(prisma, { provider: "postgresql" }),
  emailAndPassword: { enabled: true },
  socialProviders: {
    google: {
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    },
  },
  session: {
    expiresIn: 60 * 60 * 24 * 7, // 7 days
  },
});

Web Usage

// Web app
import { authClient } from "@repo/auth-utils/client";

// Login
await authClient.signIn.email({ email, password });

// Social login
await authClient.signIn.social({ provider: "google" });

// Get session
const session = await authClient.getSession();

// Logout
await authClient.signOut();

Mobile Usage

// React Native app
import { authClient } from "@repo/auth-utils/client";

// Same API as web
await authClient.signIn.email({ email, password });
const session = await authClient.getSession();

Role-Based Access

// Helper functions
import { isSessionAdmin, isAdmin } from "@repo/auth-utils/helpers";

// Check if user is admin
const userIsAdmin = isSessionAdmin(session);
const directCheck = isAdmin(user);

// In components
if (isSessionAdmin(session)) {
  return <AdminPanel />;
}

Environment Variables

BETTER_AUTH_SECRET="your-32-character-secret"
BETTER_AUTH_URL="http://localhost:3001"

# Optional OAuth
GOOGLE_CLIENT_ID="your-google-client-id"
GOOGLE_CLIENT_SECRET="your-google-client-secret"

Server-Side Protection

// API routes
import { auth } from "@repo/auth-utils";

export async function GET(request: Request) {
  const session = await auth.api.getSession({ headers: request.headers });
  
  if (!session) {
    return new Response("Unauthorized", { status: 401 });
  }
  
  return Response.json({ user: session.user });
}

User Types

export type UserRole = "admin" | "user";

export interface UserWithRole extends User {
  role: UserRole;
}

The auth system works identically on web and mobile with Better-auth handling the platform differences automatically.