Guide

Authentication

Add authentication to your UNuxt application

UNuxt uses Better Auth for a complete authentication system with multiple providers and security features.

Add email/password authentication

The default setup includes email and password authentication. Users can register and login through the auth pages:

  • /auth/register - User registration
  • /auth/login - User login
  • /auth/forgot-password - Password reset

Configure OAuth providers

Add OAuth providers by setting environment variables and configuring Better Auth.

Set up Google OAuth

  1. Create credentials in Google Cloud Console
  2. Add your environment variables:
.env
GOOGLE_CLIENT_ID=your-client-id
GOOGLE_CLIENT_SECRET=your-client-secret

Set up GitHub OAuth

  1. Create an OAuth app in GitHub Developer Settings
  2. Add your environment variables:
.env
GITHUB_CLIENT_ID=your-client-id
GITHUB_CLIENT_SECRET=your-client-secret

Protect your routes

Use middleware to protect routes that require authentication:

middleware/auth.ts
export default defineNuxtRouteMiddleware((to) => {
  const { loggedIn } = useUserSession()

  if (!loggedIn.value) {
    return navigateTo('/auth/login')
  }
})

Apply the middleware to protected pages:

pages/dashboard.vue
<script setup lang="ts">
definePageMeta({
  middleware: 'auth'
})
</script>

Handle user sessions

Access the current user session with the useUserSession composable:

components/UserProfile.vue
<script setup lang="ts">
const { user, session, loggedIn, clear } = useUserSession()

async function handleLogout() {
  await clear()
  navigateTo('/auth/login')
}
</script>

<template>
  <div v-if="loggedIn">
    <p>Welcome, {{ user.name }}</p>
    <UButton @click="handleLogout">Logout</UButton>
  </div>
</template>

Enable two-factor authentication

Better Auth supports 2FA out of the box. Users can enable it in their account settings:

composables/use2FA.ts
export function use2FA() {
  const { $auth } = useNuxtApp()

  async function enable2FA() {
    const { data } = await $auth.twoFactor.enable()
    return data.qrCode
  }

  async function verify2FA(code: string) {
    await $auth.twoFactor.verify({ code })
  }

  return { enable2FA, verify2FA }
}

Next steps

Copyright © 2026