Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .nuxtrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
imports.autoImport=false
typescript.includeWorkspace=true
abckit.npm=true
experimental.typescriptBundlerResolution=true
setups.@onmax/nuxt-better-auth="0.0.2-alpha.19"
setups.better-auth-nuxt="0.0.10-beta.21"
3 changes: 3 additions & 0 deletions auth.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { defineClientAuth } from '@onmax/nuxt-better-auth/config'

export default defineClientAuth({})
21 changes: 13 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@onmax/nuxt-better-auth",
"name": "better-auth-nuxt",
"type": "module",
"version": "0.0.2-alpha.19",
"version": "0.0.10-beta.25",
"packageManager": "[email protected]",
"description": "Nuxt module for Better Auth integration with NuxtHub, route protection, session management, and role-based access",
"author": "onmax",
Expand Down Expand Up @@ -54,10 +54,10 @@
"prepack": "nuxt-module-build build",
"dev": "pnpm dev:prepare && nuxi dev playground",
"dev:build": "nuxi build playground",
"dev:prepare": "nuxt-module-build build --stub && nuxi prepare playground",
"dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxi prepare playground",
"dev:docs": "nuxi dev docs",
"build:docs": "nuxi build docs",
"release": "bumpp --push --no-push-all",
"release": "pnpm publish --no-git-checks --access public --tag beta",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"typecheck": "vue-tsc --noEmit",
Expand All @@ -80,8 +80,6 @@
},
"dependencies": {
"@better-auth/cli": "^1.5.0-beta.3",
"@nuxt/kit": "^4.2.2",
"@nuxt/ui": "^4.2.1",
"defu": "^6.1.4",
"jiti": "^2.4.2",
"pathe": "^2.0.3",
Expand All @@ -93,9 +91,11 @@
"@libsql/client": "^0.15.15",
"@nuxt/devtools": "^3.1.1",
"@nuxt/devtools-kit": "^3.1.1",
"@nuxt/kit": "https://pkg.pr.new/@nuxt/kit@33005",
"@nuxt/module-builder": "^1.0.2",
"@nuxt/schema": "^4.2.2",
"@nuxt/schema": "https://pkg.pr.new/@nuxt/schema@33005",
"@nuxt/test-utils": "^3.21.0",
"@nuxt/ui": "^4.2.1",
"@nuxthub/core": "^0.10.5",
"@types/better-sqlite3": "^7.6.13",
"@types/node": "latest",
Expand All @@ -107,8 +107,9 @@
"drizzle-kit": "^0.31.8",
"drizzle-orm": "^0.38.4",
"eslint": "^9.39.1",
"nitro": "3.0.1-alpha.2",
"npm-agentskills": "https://pkg.pr.new/onmax/npm-agentskills@394499e",
"nuxt": "^4.2.2",
"nuxt": "https://pkg.pr.new/nuxt@33005",
"tinyexec": "^1.0.2",
"typescript": "~5.9.3",
"vitest": "^4.0.15",
Expand All @@ -129,6 +130,10 @@
"[email protected]": "patches/[email protected]"
},
"overrides": {
"@nuxt/kit": "https://pkg.pr.new/@nuxt/kit@33005",
"@nuxt/schema": "https://pkg.pr.new/@nuxt/schema@33005",
"nitro": "3.0.1-alpha.2",
"nuxt": "https://pkg.pr.new/nuxt@33005",
"reka-ui": "^2.6.1"
}
}
Expand Down
4,191 changes: 1,930 additions & 2,261 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions server/auth.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { defineServerAuth } from '@onmax/nuxt-better-auth/config'

export default defineServerAuth({
emailAndPassword: { enabled: true },
})
90 changes: 72 additions & 18 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { BetterAuthPlugin } from 'better-auth'
import type { BetterAuthModuleOptions } from './runtime/config'
import type { AuthRouteRules } from './runtime/types'
import type { CasingOption } from './schema-generator'
import type { ClientExtendConfig } from './types/hooks'
import { randomBytes } from 'node:crypto'
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
import { mkdir, writeFile } from 'node:fs/promises'
Expand Down Expand Up @@ -144,7 +145,7 @@ async function promptForSecret(rootDir: string): Promise<string | undefined> {
export type { BetterAuthModuleOptions } from './runtime/config'

export default defineNuxtModule<BetterAuthModuleOptions>({
meta: { name: '@onmax/nuxt-better-auth', version, configKey: 'auth', compatibility: { nuxt: '>=3.0.0' } },
meta: { name: 'better-auth-nuxt', version, configKey: 'auth', compatibility: { nuxt: '>=3.0.0' } },
defaults: {
clientOnly: false,
serverConfig: 'server/auth.config',
Expand All @@ -161,14 +162,14 @@ export default defineNuxtModule<BetterAuthModuleOptions>({
const serverPath = join(nuxt.options.rootDir, 'server/auth.config.ts')
const clientPath = join(nuxt.options.srcDir, 'auth.config.ts')

const serverTemplate = `import { defineServerAuth } from '@onmax/nuxt-better-auth/config'
const serverTemplate = `import { defineServerAuth } from 'better-auth-nuxt/config'

export default defineServerAuth({
emailAndPassword: { enabled: true },
})
`

const clientTemplate = `import { defineClientAuth } from '@onmax/nuxt-better-auth/config'
const clientTemplate = `import { defineClientAuth } from 'better-auth-nuxt/config'

export default defineClientAuth({})
`
Expand Down Expand Up @@ -324,7 +325,7 @@ export { db }`
{ convexUrl },
)
databaseCode = `import { useRuntimeConfig } from '#imports'
import { createConvexHttpAdapter } from '@onmax/nuxt-better-auth/adapters/convex'
import { createConvexHttpAdapter } from 'better-auth-nuxt/adapters/convex'
import { api } from '#convex/api'

export function createDatabase() {
Expand Down Expand Up @@ -393,7 +394,7 @@ interface _AugmentedServerAuthContext {
${hasHubDb ? `db: typeof import('@nuxthub/db')['db']` : 'db: unknown'}
}

declare module '@onmax/nuxt-better-auth/config' {
declare module 'better-auth-nuxt/config' {
import type { BetterAuthOptions } from 'better-auth'
type ServerAuthConfig = Omit<BetterAuthOptions, 'database' | 'secret' | 'baseURL'>
export function defineServerAuth<T extends ServerAuthConfig>(config: T | ((ctx: _AugmentedServerAuthContext) => T)): (ctx: _AugmentedServerAuthContext) => T
Expand All @@ -404,15 +405,15 @@ declare module '@onmax/nuxt-better-auth/config' {
addTypeTemplate({
filename: 'types/nuxt-better-auth-nitro.d.ts',
getContents: () => `
declare module 'nitropack' {
declare module 'nitro' {
interface NitroRouteRules {
auth?: import('${resolver.resolve('./runtime/types')}').AuthMeta
}
interface NitroRouteConfig {
auth?: import('${resolver.resolve('./runtime/types')}').AuthMeta
}
}
declare module 'nitropack/types' {
declare module 'nitro/types' {
interface NitroRouteRules {
auth?: import('${resolver.resolve('./runtime/types')}').AuthMeta
}
Expand Down Expand Up @@ -443,6 +444,59 @@ declare module '#nuxt-better-auth' {
`,
})

// Client config extension via hook
const extendedClientConfig: ClientExtendConfig = {}
await nuxt.callHook('better-auth:client:extend', extendedClientConfig)

const hasClientExtensions = extendedClientConfig.plugins && extendedClientConfig.plugins.length > 0

if (hasClientExtensions) {
// Generate import statements for each plugin
const pluginImports = extendedClientConfig.plugins!.map((plugin, index) => {
const importName = plugin.name || `plugin${index}`
return plugin.name
? `import { ${plugin.name} as ${importName} } from '${plugin.from}'`
: `import ${importName} from '${plugin.from}'`
}).join('\n')

// Generate plugin invocations (call functions with options if provided)
const pluginInvocations = extendedClientConfig.plugins!.map((plugin, index) => {
const importName = plugin.name || `plugin${index}`
if (plugin.options) {
return `${importName}(${JSON.stringify(plugin.options)})`
}
return `${importName}()`
}).join(', ')

// Generate a wrapper that merges user config with extended plugins
// Returns config object (not client) - client is created in useUserSession
const clientExtensionsCode = `
import getUserClientConfig from '${clientConfigPath}'
${pluginImports}

// Extended plugins from better-auth:client:extend hook
const extendedPlugins = [${pluginInvocations}]

export default function getClientConfig(baseURL) {
// Get user's config
const userConfig = getUserClientConfig(baseURL)

// Merge extended plugins with user plugins
return {
...userConfig,
plugins: [...extendedPlugins, ...(userConfig.plugins || [])],
}
}
`
const clientExtTemplate = addTemplate({
filename: 'better-auth/client-extended.mjs',
getContents: () => clientExtensionsCode,
write: true,
})
nuxt.options.alias['#auth/client'] = clientExtTemplate.dst
consola.info('Client config extended via better-auth:client:extend hook')
}

// HMR
nuxt.hook('builder:watch', async (_event, relativePath) => {
if (relativePath.includes('auth.config')) {
Expand Down Expand Up @@ -481,19 +535,19 @@ declare module '#nuxt-better-auth' {
const isProduction = process.env.NODE_ENV === 'production' || !nuxt.options.dev
if (!isProduction && !clientOnly) {
// Devtools UI requires Nuxt UI components (UTable, UTabs, etc.)
if (!hasNuxtModule('@nuxt/ui'))
await installModule('@nuxt/ui')
setupDevTools(nuxt)
addServerHandler({ route: '/api/_better-auth/config', method: 'get', handler: resolver.resolve('./runtime/server/api/_better-auth/config.get') })
// if (!hasNuxtModule('@nuxt/ui'))
// await installModule('@nuxt/ui')
// setupDevTools(nuxt)
addServerHandler({ route: '/api/_better-auth/config', method: 'GET', handler: resolver.resolve('./runtime/server/api/_better-auth/config.get') })
if (hasHubDb) {
addServerHandler({ route: '/api/_better-auth/sessions', method: 'get', handler: resolver.resolve('./runtime/server/api/_better-auth/sessions.get') })
addServerHandler({ route: '/api/_better-auth/sessions', method: 'delete', handler: resolver.resolve('./runtime/server/api/_better-auth/sessions.delete') })
addServerHandler({ route: '/api/_better-auth/users', method: 'get', handler: resolver.resolve('./runtime/server/api/_better-auth/users.get') })
addServerHandler({ route: '/api/_better-auth/accounts', method: 'get', handler: resolver.resolve('./runtime/server/api/_better-auth/accounts.get') })
addServerHandler({ route: '/api/_better-auth/sessions', method: 'GET', handler: resolver.resolve('./runtime/server/api/_better-auth/sessions.get') })
addServerHandler({ route: '/api/_better-auth/sessions', method: 'DELETE', handler: resolver.resolve('./runtime/server/api/_better-auth/sessions.delete') })
addServerHandler({ route: '/api/_better-auth/users', method: 'GET', handler: resolver.resolve('./runtime/server/api/_better-auth/users.get') })
addServerHandler({ route: '/api/_better-auth/accounts', method: 'GET', handler: resolver.resolve('./runtime/server/api/_better-auth/accounts.get') })
}
extendPages((pages) => {
pages.push({ name: 'better-auth-devtools', path: '/__better-auth-devtools', file: resolver.resolve('./runtime/app/pages/__better-auth-devtools.vue') })
})
// extendPages((pages) => {
// pages.push({ name: 'better-auth-devtools', path: '/__better-auth-devtools', file: resolver.resolve('./runtime/app/pages/__better-auth-devtools.vue') })
// })
}

nuxt.hook('pages:extend', (pages) => {
Expand Down
34 changes: 20 additions & 14 deletions src/runtime/app/composables/useUserSession.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,45 @@
import type { AppAuthClient, AuthSession, AuthUser } from '#nuxt-better-auth'
import type { AuthSession, AuthUser } from '#nuxt-better-auth'
import type { ComputedRef, Ref } from 'vue'
import createAppAuthClient from '#auth/client'
import getClientConfig from '#auth/client'
import { computed, nextTick, useRequestHeaders, useRequestURL, useRuntimeConfig, useState, watch } from '#imports'
import { createAuthClient } from 'better-auth/vue'

// Create the actual auth client from config
type AuthClient = ReturnType<typeof createAuthClient>

export interface SignOutOptions { onSuccess?: () => void | Promise<void> }

export interface UseUserSessionReturn {
client: AppAuthClient | null
client: AuthClient | null
session: Ref<AuthSession | null>
user: Ref<AuthUser | null>
loggedIn: ComputedRef<boolean>
ready: ComputedRef<boolean>
signIn: NonNullable<AppAuthClient>['signIn']
signUp: NonNullable<AppAuthClient>['signUp']
signIn: NonNullable<AuthClient>['signIn']
signUp: NonNullable<AuthClient>['signUp']
signOut: (options?: SignOutOptions) => Promise<void>
waitForSession: () => Promise<void>
fetchSession: (options?: { headers?: HeadersInit, force?: boolean }) => Promise<void>
updateUser: (updates: Partial<AuthUser>) => void
}

// Singleton client instance to ensure consistent state across all useUserSession calls
let _client: AppAuthClient | null = null
function getClient(baseURL: string): AppAuthClient {
if (!_client)
_client = createAppAuthClient(baseURL)
return _client
let _client: AuthClient | null = null
function getClient(baseURL: string): AuthClient {
if (!_client) {
const config = getClientConfig(baseURL)
_client = createAuthClient(config)
}
return _client!
}

export function useUserSession(): UseUserSessionReturn {
const runtimeConfig = useRuntimeConfig()
const requestURL = useRequestURL()

// Client only - create better-auth client for client-side operations (singleton)
const client: AppAuthClient | null = import.meta.client
? getClient(runtimeConfig.public.siteUrl || requestURL.origin)
const client: AuthClient | null = import.meta.client
? getClient((runtimeConfig.public.siteUrl as string) || requestURL.origin)
: null

// Shared state via useState for SSR hydration
Expand Down Expand Up @@ -99,8 +105,8 @@ export function useUserSession(): UseUserSessionReturn {
}

// Wrap signIn methods to wait for session sync before calling onSuccess
type SignIn = NonNullable<AppAuthClient>['signIn']
type SignUp = NonNullable<AppAuthClient>['signUp']
type SignIn = NonNullable<AuthClient>['signIn']
type SignUp = NonNullable<AuthClient>['signUp']

// Wraps onSuccess callback to sync session before executing
function wrapOnSuccess(cb: (ctx: unknown) => void | Promise<void>) {
Expand Down
4 changes: 2 additions & 2 deletions src/runtime/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@ export function defineServerAuth<T extends ServerAuthConfig>(config: T | ((ctx:
return typeof config === 'function' ? config : () => config
}

export function defineClientAuth<T extends ClientAuthConfig>(config: T | ((ctx: ClientAuthContext) => T)): (baseURL: string) => ReturnType<typeof createAuthClient<T>> {
export function defineClientAuth<T extends ClientAuthConfig>(config: T | ((ctx: ClientAuthContext) => T)): (baseURL: string) => T & { baseURL: string } {
return (baseURL: string) => {
const ctx: ClientAuthContext = { siteUrl: baseURL }
const resolved = typeof config === 'function' ? config(ctx) : config
return createAuthClient({ ...resolved, baseURL })
return { ...resolved, baseURL }
}
}
2 changes: 1 addition & 1 deletion src/runtime/server/api/_better-auth/accounts.get.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { defineEventHandler, getQuery } from 'h3'
import { defineEventHandler, getQuery } from 'nitro/h3'
import { paginationQuerySchema, sanitizeSearchPattern } from './_schema'

export default defineEventHandler(async (event) => {
Expand Down
4 changes: 2 additions & 2 deletions src/runtime/server/api/_better-auth/config.get.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { defineEventHandler } from 'h3'
import { useRuntimeConfig } from 'nitropack/runtime'
import { defineEventHandler } from 'nitro/h3'
import { useRuntimeConfig } from 'nitro/runtime-config'
import { serverAuth } from '../../utils/auth'

export default defineEventHandler(async (event) => {
Expand Down
8 changes: 4 additions & 4 deletions src/runtime/server/api/_better-auth/sessions.delete.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createError, defineEventHandler, readBody } from 'h3'
import { defineEventHandler, HTTPError, readBody } from 'nitro/h3'
import { z } from 'zod'

const deleteSessionSchema = z.object({
Expand All @@ -11,7 +11,7 @@ export default defineEventHandler(async (event) => {

const { db, schema } = await import('@nuxthub/db')
if (!schema.session)
throw createError({ statusCode: 500, message: 'Session table not found' })
throw new HTTPError('Session table not found', { status: 500 })

const { eq } = await import('drizzle-orm')
await db.delete(schema.session).where(eq(schema.session.id, body.id))
Expand All @@ -20,9 +20,9 @@ export default defineEventHandler(async (event) => {
}
catch (error: unknown) {
if (error instanceof z.ZodError) {
throw createError({ statusCode: 400, message: error.errors[0]?.message || 'Invalid request' })
throw new HTTPError(error.errors[0]?.message || 'Invalid request', { status: 400 })
}
console.error('[DevTools] Delete session failed:', error)
throw createError({ statusCode: 500, message: 'Failed to delete session' })
throw new HTTPError('Failed to delete session', { status: 500 })
}
})
2 changes: 1 addition & 1 deletion src/runtime/server/api/_better-auth/sessions.get.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { defineEventHandler, getQuery } from 'h3'
import { defineEventHandler, getQuery } from 'nitro/h3'
import { paginationQuerySchema, sanitizeSearchPattern } from './_schema'

export default defineEventHandler(async (event) => {
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/server/api/_better-auth/users.get.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { defineEventHandler, getQuery } from 'h3'
import { defineEventHandler, getQuery } from 'nitro/h3'
import { paginationQuerySchema, sanitizeSearchPattern } from './_schema'

export default defineEventHandler(async (event) => {
Expand Down
6 changes: 3 additions & 3 deletions src/runtime/server/api/auth/[...all].ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { H3Event } from 'h3'
import { defineEventHandler, toWebRequest } from 'h3'
import type { H3Event } from 'nitro/h3'
import { defineEventHandler } from 'nitro/h3'
import { serverAuth } from '../../utils/auth'

export default defineEventHandler(async (event: H3Event) => {
const auth = serverAuth(event)
return auth.handler(toWebRequest(event))
return auth.handler(event.req)
})
Loading