NuxtN
Nuxt9mo ago
5 replies
lazygopher

Understanding useSession behavior in Nuxt with Better-Auth and NuxtUI

I'm using Better-Auth for authentication and ran into some confusion while trying to implement a simple feature: showing a Login button in the menu when the user is not authenticated, and Sign Out when they are. I'm also using NuxtUI for the UI components.

After a lot of trial and error, I got it working with the code below, but I got questions:

1. Why does using await to useSession() fix it?
2. Would it make sense to disable SSR for this component to simplify or optimize things?

# menu.vue
<script setup lang="ts">
import type { DropdownMenuItem } from "@nuxt/ui"
import { useSession, signOut } from "~/lib/auth-client"
const { data: session } = await useSession(useFetch)
const loggedIn = computed(() => !!session?.value?.user)
const items = computed<DropdownMenuItem[]>(() => {
  const baseItems = [..]
  return loggedIn.value
   ? [
     ...baseItems,
     {
      label: "Sign Out",
      icon: "i-lucide-log-out",
      onSelect: () => {
       signOut(),
       },
      },
     },
    ]
   : [{ label: "Login", icon: "i-lucide-log-in", to: "/login" }, ...baseItems]
})
</script>
<template>
  <UDropdownMenu
   :items="items"
   :content="{
    align: 'start',
    side: 'bottom',
    sideOffset: 8,
   }"
   :ui="{
    content: 'w-48',
   }"
  >
   <UButton icon="i-lucide-menu" color="neutral" variant="outline" />
  </UDropdownMenu>
</template>
Was this page helpful?