Client-side redirects improve UX but don't prevent unauthorized access. Always validate on the server.
Better Auth performs origin checks for cookie-based requests (it validates Origin / Referer). If you use multiple domains (custom domains, preview URLs, etc.), add them to trustedOrigins in your auth config.
import { defineServerAuth } from '@onmax/nuxt-better-auth/config'
export default defineServerAuth({
trustedOrigins: [
'http://localhost:3000',
'https://your-domain.com',
],
})
The built-in Nitro middleware only checks routeRules.auth for /api/**.
By default, unauthorized requests to protected routes receive a 401 response. To customize:
Redirect to login instead of 401:
export default defineEventHandler(async (event) => {
const session = await getUserSession(event)
if (!session && event.path.startsWith('/api/protected')) {
throw createError({ statusCode: 401, message: 'Unauthorized' })
}
})
Return JSON error for API routes:
// This is the default behavior for /api/* routes
throw createError({
statusCode: 401,
data: { error: 'Authentication required' }
})
If you want different behavior (e.g. enforce auth: 'user' for APIs), add your own Nitro middleware and/or call requireUserSession(event) directly inside handlers.
export default defineEventHandler(async (event) => {
await requireUserSession(event)
return { ok: true }
})
Unauthenticated users are redirected to /login when a page requires auth. If your app uses a different login path, create a /login route or implement your own route middleware.
redirects.login to a route that doesn't exist, users will see a 404 error when authentication is required. Ensure your login page exists at the configured path.This module does not include built-in rate limiting. Authentication endpoints can be targeted by brute force attacks.
Recommendations:
DevTools are automatically disabled when NODE_ENV=production. The /api/_better-auth/* endpoints and devtools page are never registered in production builds.