Authentication

End-to-end user authentication, session cookies, and route handlers with Better Auth.

Authentication Package (`@repo/auth`)

Morax provides complete authentication out-of-the-box using Better Auth, tightly integrated with your shared Drizzle database and environment configuration.

Better Auth Setup

The authentication engine is defined once in packages/auth:

packages/auth/src/index.ts
// packages/auth/src/index.ts
import { betterAuth } from 'better-auth';
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
import { db } from '@repo/db';
import { env } from '@repo/env';

export const auth = betterAuth({
  database: drizzleAdapter(db, {
    provider: 'pg',
  }),
  emailAndPassword: {
    enabled: true,
  },
  secret: env.BETTER_AUTH_SECRET,
  baseURL: env.BETTER_AUTH_URL,
});

Mounting Auth Endpoints

You can mount the authentication router in Hono, Express, or Next.js with one line:

Mounting Auth Routes
// Inside your server or Next.js route handler
import { auth } from '@repo/auth';
import { toNodeHandler } from 'better-auth/node';

// All auth routes (/api/auth/*) handled automatically
app.all('/api/auth/*', toNodeHandler(auth));

Client Authentication

In your frontend applications, instantiate the client to sign in and read sessions:

React Client Hook
import { createAuthClient } from 'better-auth/react';

export const authClient = createAuthClient({
  baseURL: 'http://localhost:3000',
});

// React Hook
export function UserProfile() {
  const { data: session, isPending } = authClient.useSession();

  if (isPending) return <div>Loading...</div>;
  if (!session) return <div>Not signed in</div>;

  return <div>Welcome, {session.user.name}!</div>;
}

Route Protection

Verify sessions on incoming requests before executing protected business logic:

Session Verification
const session = await auth.api.getSession({
  headers: req.headers,
});

if (!session) {
  return res.status(401).json({ error: 'Unauthorized' });
}