simplify better-auth integration in elysia routes

This commit is contained in:
2026-02-24 21:04:06 -05:00
parent 122030e487
commit ae9f081f90
6 changed files with 53 additions and 160 deletions

View File

@@ -1,5 +1,5 @@
import { createAuthClient } from 'better-auth/react';
import { adminClient, magicLinkClient, organizationClient } from 'better-auth/client/plugins';
import { magicLinkClient } from 'better-auth/client/plugins';
import { resolveApiBaseURL } from '@/lib/runtime-url';
const baseURL = resolveApiBaseURL(process.env.NEXT_PUBLIC_API_URL);
@@ -7,8 +7,6 @@ const baseURL = resolveApiBaseURL(process.env.NEXT_PUBLIC_API_URL);
export const authClient = createAuthClient({
baseURL: baseURL || undefined,
plugins: [
adminClient(),
magicLinkClient(),
organizationClient()
magicLinkClient()
]
});

View File

@@ -1,14 +1,10 @@
import { betterAuth } from 'better-auth';
import { drizzleAdapter } from 'better-auth/adapters/drizzle';
import { nextCookies } from 'better-auth/next-js';
import { admin, magicLink, organization } from 'better-auth/plugins';
import { magicLink } from 'better-auth/plugins';
import { db } from '@/lib/server/db';
import { authSchema } from '@/lib/server/db/schema';
type BetterAuthInstance = ReturnType<typeof betterAuth>;
let authInstance: BetterAuthInstance | null = null;
function parseCsvList(value: string | undefined) {
return (value ?? '')
.split(',')
@@ -16,46 +12,29 @@ function parseCsvList(value: string | undefined) {
.filter((entry) => entry.length > 0);
}
function buildAuth() {
const adminUserIds = parseCsvList(process.env.BETTER_AUTH_ADMIN_USER_IDS);
const trustedOrigins = parseCsvList(process.env.BETTER_AUTH_TRUSTED_ORIGINS);
const baseURL = process.env.BETTER_AUTH_BASE_URL?.trim()
|| process.env.BETTER_AUTH_URL?.trim()
|| undefined;
const secret = process.env.BETTER_AUTH_SECRET?.trim() || undefined;
const trustedOrigins = parseCsvList(process.env.BETTER_AUTH_TRUSTED_ORIGINS);
const baseURL = process.env.BETTER_AUTH_BASE_URL?.trim()
|| process.env.BETTER_AUTH_URL?.trim()
|| undefined;
const secret = process.env.BETTER_AUTH_SECRET?.trim() || undefined;
return betterAuth({
database: drizzleAdapter(db, {
provider: 'pg',
schema: authSchema
export const auth = betterAuth({
database: drizzleAdapter(db, {
provider: 'pg',
schema: authSchema
}),
baseURL,
secret,
emailAndPassword: {
enabled: true
},
trustedOrigins: trustedOrigins.length > 0 ? trustedOrigins : undefined,
plugins: [
magicLink({
sendMagicLink: async ({ email, url }) => {
console.info(`[better-auth] Magic link requested for ${email}: ${url}`);
}
}),
baseURL,
secret,
emailAndPassword: {
enabled: true
},
trustedOrigins: trustedOrigins.length > 0 ? trustedOrigins : undefined,
plugins: [
admin(adminUserIds.length > 0 ? { adminUserIds } : undefined),
magicLink({
sendMagicLink: async ({ email, url }) => {
console.info(`[better-auth] Magic link requested for ${email}: ${url}`);
}
}),
organization(),
nextCookies()
]
});
}
export function getAuth() {
if (!authInstance) {
authInstance = buildAuth();
}
return authInstance;
}
export async function ensureAuthSchema() {
return getAuth();
}
nextCookies()
]
});

View File

@@ -1,109 +1,40 @@
import { headers } from 'next/headers';
import { ensureAuthSchema } from '@/lib/auth';
import { auth } from '@/lib/auth';
import { asErrorMessage, jsonError } from '@/lib/server/http';
type RecordValue = Record<string, unknown>;
export type AuthenticatedSession = NonNullable<
Awaited<ReturnType<typeof auth.api.getSession>>
>;
export type AuthenticatedUser = {
id: string;
email: string;
name: string | null;
image: string | null;
role?: string | string[];
};
export type AuthenticatedSession = {
user: AuthenticatedUser;
session: RecordValue | null;
raw: RecordValue;
};
const UNAUTHORIZED_SESSION: AuthenticatedSession = {
user: {
id: '',
email: '',
name: null,
image: null
},
session: null,
raw: {}
};
function asRecord(value: unknown): RecordValue | null {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return null;
type RequiredSessionResult = (
| {
session: AuthenticatedSession;
response: null;
}
return value as RecordValue;
}
function asString(value: unknown) {
return typeof value === 'string' && value.trim().length > 0 ? value : null;
}
function asNullableString(value: unknown) {
return typeof value === 'string' ? value : null;
}
function normalizeRole(value: unknown) {
if (typeof value === 'string') {
return value;
| {
session: null;
response: Response;
}
if (Array.isArray(value)) {
const roles = value.filter((entry): entry is string => typeof entry === 'string');
return roles.length > 0 ? roles : undefined;
}
return undefined;
}
function normalizeSession(rawSession: unknown): AuthenticatedSession | null {
const root = asRecord(rawSession);
if (!root) {
return null;
}
const rootSession = asRecord(root.session);
const userRecord = asRecord(root.user) ?? asRecord(rootSession?.user);
if (!userRecord) {
return null;
}
const id = asString(userRecord.id);
const email = asString(userRecord.email);
if (!id || !email) {
return null;
}
return {
user: {
id,
email,
name: asNullableString(userRecord.name),
image: asNullableString(userRecord.image),
role: normalizeRole(userRecord.role)
},
session: rootSession,
raw: root
};
}
);
export async function getAuthenticatedSession() {
const auth = await ensureAuthSchema();
const session = await auth.api.getSession({
headers: await headers()
});
return normalizeSession(session);
if (!session?.user?.id) {
return null;
}
return session;
}
export async function requireAuthenticatedSession() {
export async function requireAuthenticatedSession(): Promise<RequiredSessionResult> {
try {
const session = await getAuthenticatedSession();
if (!session) {
return {
session: UNAUTHORIZED_SESSION,
session: null,
response: jsonError('Unauthorized', 401)
};
}
@@ -114,7 +45,7 @@ export async function requireAuthenticatedSession() {
};
} catch (error) {
return {
session: UNAUTHORIZED_SESSION,
session: null,
response: jsonError(asErrorMessage(error, 'Authentication subsystem is unavailable.'), 500)
};
}