// Grey Haven's authentication patterns using better-auth - magic links, passkeys, OAuth providers, session management with Redis, JWT claims with tenant_id, and Doppler for auth secrets. Use when implementing authentication features.
| name | grey-haven-authentication-patterns |
| description | Grey Haven's authentication patterns using better-auth - magic links, passkeys, OAuth providers, session management with Redis, JWT claims with tenant_id, and Doppler for auth secrets. Use when implementing authentication features. |
Follow Grey Haven Studio's authentication patterns using better-auth for TanStack Start projects with multi-tenant support.
ALWAYS include tenant_id in auth tables:
export const users = pgTable("users", {
id: uuid("id").primaryKey().defaultRandom(),
tenant_id: uuid("tenant_id").notNull(), // CRITICAL!
email_address: text("email_address").notNull().unique(),
// ... other fields
});
export const sessions = pgTable("sessions", {
id: uuid("id").primaryKey().defaultRandom(),
user_id: uuid("user_id").references(() => users.id),
tenant_id: uuid("tenant_id").notNull(), // CRITICAL!
// ... other fields
});
NEVER commit auth secrets:
# Doppler provides these at runtime
BETTER_AUTH_SECRET=<generated-secret>
BETTER_AUTH_URL=https://app.example.com
GOOGLE_CLIENT_ID=<from-google-console>
GOOGLE_CLIENT_SECRET=<from-google-console>
// lib/server/auth.ts
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "@better-auth/drizzle";
import { db } from "~/lib/server/db";
export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: "pg",
schema,
}),
emailAndPassword: {
enabled: true,
requireEmailVerification: true,
},
secret: process.env.BETTER_AUTH_SECRET!,
baseURL: process.env.BETTER_AUTH_URL!,
trustedOrigins: [process.env.BETTER_AUTH_URL!],
});
// Sign up with email verification
await auth.signUp.email({
email: "user@example.com",
password: "secure-password",
name: "John Doe",
data: {
tenant_id: tenantId, // Include tenant context
},
});
// Sign in
await auth.signIn.email({
email: "user@example.com",
password: "secure-password",
});
// Send magic link
await auth.magicLink.send({
email: "user@example.com",
callbackURL: "/auth/verify",
});
// Verify magic link token
await auth.magicLink.verify({
token: tokenFromEmail,
});
// Google OAuth
export const auth = betterAuth({
// ... other config
socialProviders: {
google: {
clientId: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
scopes: ["email", "profile"],
},
},
});
// Redirect to Google
await auth.signIn.social({
provider: "google",
callbackURL: "/auth/callback",
});
// Enable passkeys
export const auth = betterAuth({
// ... other config
passkey: {
enabled: true,
},
});
// Register passkey
await auth.passkey.register({
name: "My MacBook",
});
// Authenticate with passkey
await auth.passkey.authenticate();
// Middleware to extract tenant from JWT
export async function getTenantFromSession() {
const session = await auth.api.getSession();
if (!session) {
throw new Error("Not authenticated");
}
return {
userId: session.user.id,
tenantId: session.user.tenant_id, // From JWT claims
user: session.user,
};
}
// Use Upstash Redis for sessions
export const auth = betterAuth({
// ... other config
session: {
expiresIn: 60 * 60 * 24 * 7, // 7 days
updateAge: 60 * 60 * 24, // Refresh daily
cookieCache: {
enabled: true,
maxAge: 5 * 60, // 5 minutes
},
},
});
// routes/_authenticated/_layout.tsx
import { createFileRoute, redirect } from "@tanstack/react-router";
import { getTenantFromSession } from "~/lib/server/auth";
export const Route = createFileRoute("/_authenticated/_layout")({
beforeLoad: async () => {
try {
const { userId, tenantId, user } = await getTenantFromSession();
return { session: { userId, tenantId, user } };
} catch {
throw redirect({
to: "/auth/login",
search: { redirect: location.href },
});
}
},
});
All supporting files are under 500 lines per Anthropic best practices:
examples/ - Complete auth examples
reference/ - Auth references
templates/ - Copy-paste ready templates
checklists/ - Security checklists
Use this skill when:
These patterns are from Grey Haven's production templates: