N
Nuxt3d ago
Howler

What is the idiomatic Nuxt v3.16 way of Authentication/Authorization ?

I am trying Better-Auth, but its been a real challenge. I am still new to Nuxt and I am still learning. What are the security frameworks/utilities that work great with Nuxt? I don't want to use a third party service. I plan on keeping all of my users, accounts, roles, permissions in my database. Sugggestions?
2 Replies
kapa.ai
kapa.ai3d ago
Hi @Howler. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- For Nuxt 3.16, the recommended approach for authentication and authorization is using the nuxt-auth-utils module, which provides utilities for managing both client-side and server-side session data without requiring a third-party service. Using nuxt-auth-utils This official module allows you to: - Store user session data in secured & sealed cookies - Protect routes on both client and server sides - Manage authentication state easily Installation
npx nuxi@latest module add auth-utils
npx nuxi@latest module add auth-utils
This will install the module and add it to your nuxt.config.ts file Docs > Guide > Recipes > Sessions and Authentication. Basic Setup 1. Set up cookie encryption: Add a secure password to your .env file:
NUXT_SESSION_PASSWORD=a-random-password-with-at-least-32-characters

NUXT_SESSION_PASSWORD=a-random-password-with-at-least-32-characters

2. Create login API endpoint:
// server/api/login.post.ts
export default defineEventHandler(async (event) => {
// Validate credentials against your database
// ...

// If valid, set the user session
await setUserSession(event, {
user: {
// User data from your database
id: user.id,
name: user.name,
// Add roles, permissions, etc.
}
})
return {}
})

// server/api/login.post.ts
export default defineEventHandler(async (event) => {
// Validate credentials against your database
// ...

// If valid, set the user session
await setUserSession(event, {
user: {
// User data from your database
id: user.id,
name: user.name,
// Add roles, permissions, etc.
}
})
return {}
})

3. Protect API routes:
// server/api/protected-route.get.ts
export default defineEventHandler(async (event) => {
// This will throw a 401 error if not authenticated
const { user } = await requireUserSession(event)

// Access is granted, continue with your logic
return {}
})

// server/api/protected-route.get.ts
export default defineEventHandler(async (event) => {
// This will throw a 401 error if not authenticated
const { user } = await requireUserSession(event)

// Access is granted, continue with your logic
return {}
})

4. Protect client-side routes with middleware:
// middleware/authenticated.ts
export default defineNuxtRouteMiddleware(() => {
const { loggedIn } = useUserSession()

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

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

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

5. Apply middleware to your pages:
<script setup>
definePageMeta({
middleware: ['authenticated']
})
</script>

<script setup>
definePageMeta({
middleware: ['authenticated']
})
</script>

Working with Your Database Since you want to keep users, accounts, roles, and permissions in your database: 1. You can use Nitro SQL Database or NuxtHub SQL Database for database integration 2. Implement password hashing using the utilities provided by nuxt-auth-utils 3. Create custom middleware to check for specific roles/permissions Example Implementation For a complete implementation example, you can check out the open-source atidone repository which demonstrates a Nuxt app with authentication, database integration, and CRUD operations Docs > Guide > Recipes > Sessions and Authentication > Conclusion. If you're experiencing challenges with Better-Auth, switching to nuxt-auth-utils might provide a more straightforward experience as it's specifically designed for Nuxt 3 and maintained by the Nuxt team. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai3d ago
<@391433788590391297> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?