Authentication in Nuxt 4 with better-auth
Nuxt Starter Kit uses better-auth to provide a modern, type-safe authentication system. The authentication code is located in apps/web/layers/auth and handles login, logout, session management, and more.
Supported Authentication Methods
- Email and password
- Social login (Google & GitHub)
- Passkey (WebAuthn / FIDO2)
Better-auth Features
- Type-safe - Full TypeScript support
- Session management - Secure session handling
- Social providers - Easy OAuth integration
- Database-backed - Sessions stored in PostgreSQL
- Extensible - Plugin system for custom features
Environment Variables
Set in apps/web/.env:
# Required: at least 32 random characters, e.g. `openssl rand -base64 32`
NUXT_BETTER_AUTH_SECRET=your-secret-key-min-32-chars
# Required: better-auth uses it as its base URL
NUXT_PUBLIC_BASE_URL=http://localhost:9009
# Social login (optional)
NUXT_PRIVATE_GITHUB_CLIENT_ID=your-github-client-id
NUXT_PRIVATE_GITHUB_CLIENT_SECRET=your-github-client-secret
NUXT_PRIVATE_GOOGLE_CLIENT_ID=your-google-client-id
NUXT_PRIVATE_GOOGLE_CLIENT_SECRET=your-google-client-secret
The server doesn't start without NUXT_BETTER_AUTH_SECRET and NUXT_PUBLIC_BASE_URL.
Client-side Usage
Use the useAuth() composable (auto-imported):
<script setup lang="ts">
const { loggedIn, signIn, signOut, user } = useAuth()
async function onSignIn () {
await signIn.email({
email: '[email protected]',
password: 'password',
})
}
async function onSignOut () {
await signOut({ redirectTo: '/' })
}
</script>
<template>
<div v-if="loggedIn && user">
<p>Welcome {{ user.name }}!</p>
<button @click="onSignOut">
Sign out
</button>
</div>
<div v-else>
<button @click="onSignIn">
Sign in
</button>
</div>
</template>
The app creates one better-auth client and loads the session once. After that, better-auth's session store keeps session and user up to date, also across tabs: when a user signs out in one tab, the other tabs go to the login page on their next navigation.
useAuth() also returns isUserAdmin, isImpersonated, the Polar customer state (polarState, activeSubscription) and the underlying better-auth client.
Page Access
The global middleware apps/web/layers/auth/app/middleware/00.auth.global.ts protects every page by default. Mark public pages and guest-only pages with definePageMeta:
// a public page
definePageMeta({ auth: false })
// login and signup: only for signed-out users
definePageMeta({
auth: { only: 'guest' }
})
Server-side Usage
Require Authentication
Use requireAuth() to ensure a user is authenticated. It returns the user or throws a 401:
// server/api/protected.get.ts
export default defineEventHandler(async (event) => {
const user = await requireAuth(event)
// User is guaranteed to be authenticated here
return { message: `Hello ${user.name}!` }
})
Optional Authentication
Use getAuthSession() when authentication is optional. It returns null without a session:
// server/api/optional.get.ts
export default defineEventHandler(async (event) => {
const session = await getAuthSession(event)
if (session?.user) {
return { message: `Hello ${session.user.name}!` }
}
return { message: 'Hello guest!' }
})
Require the Admin Role
Every admin API handler starts with requireAdmin(). It returns 401 without a session and 403 without the admin role:
// server/api/dashboard/admin/my-feature/index.get.ts
export default defineEventHandler(async (event) => {
await requireAdmin(event)
// ...
})
The dashboard's admin middleware checks the role, too. Call requireAdmin() anyway: a unit test fails for every handler under server/api/dashboard/admin/ that doesn't.
Database Schema
Better-auth uses these tables (in apps/web/layers/auth/server/db/schema/auth.ts):
user- User accountssession- Active sessionsaccount- OAuth provider accountsverification- Email verification tokenspasskey- Registered passkeys
Plugins
The starter kit includes:
Polar Plugin
Integrates with Polar.sh for payments:
import { polar } from '@polar-sh/better-auth'
// Already configured in apps/web/layers/auth/server/utils/polar.ts
Social Login Setup
GitHub OAuth
- Go to GitHub Settings > Developer settings > OAuth Apps
- Create a new OAuth App
- Set Authorization callback URL to:
https://your-domain.com/api/auth/callback/github - Copy Client ID and Client Secret to
NUXT_PRIVATE_GITHUB_CLIENT_IDandNUXT_PRIVATE_GITHUB_CLIENT_SECRET
Google OAuth
- Go to Google Cloud Console
- Create a new project or select existing
- Enable Google+ API
- Create OAuth 2.0 credentials
- Add authorized redirect URI:
https://your-domain.com/api/auth/callback/google - Copy Client ID and Client Secret to
NUXT_PRIVATE_GOOGLE_CLIENT_IDandNUXT_PRIVATE_GOOGLE_CLIENT_SECRET
Customization
Authentication is configured in apps/web/layers/auth/server/utils/auth.ts. You can:
- Add more OAuth providers
- Configure session duration
- Add custom plugins
- Modify user schema
Security
Better-auth provides:
- Secure session storage
- CSRF protection
- Rate limiting per client IP in production
- Password hashing (scrypt)
- Secure cookie handling
Overview
Send transactional emails from your Nuxt app with Plunk or Resend, build templates with Nuxt Email Renderer and use the useEmail() helpers on the server.
Polar
Accept payments with Polar through the better-auth plugin: a Polar customer on sign-up, checkout for signed-in users and the customer portal.