Next.js Discord

Discord Forum

useRouter in async component

Unanswered
Oak apple gall wasp posted this in #help-forum
Open in Discord
Oak apple gall waspOP
using next-auth v5, I have an AppNavbar component, that need to be async
export default async function AppNavbar() {
    const t = await getTranslations()
    const session = await auth()

    return (
      <NavbarLink href="/" active>
        {t('nav.home')}
      </NavbarLink>
      {session ? (<div>is logged in</div>) : (
          <SignIn/>
      )
    )

I'd like to access the router to know when to set the active attribute.
But I can't, because auth requires an await or async component.

I also tried
export default function AppNavbar() {
    const t = useTranslations()
    const [session, setSession] = useState<Session | null>(null)
    useEffect(() => {
        const getSession = async () => {
            const session = await auth()
            setSession(session)
        }
        getSession()
    }, [setSession])

but
Error: 
  × You're importing a component that needs useEffect. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.

However when I "use client"
Error: 
  × It is not allowed to define inline "use server" annotated Server Actions in Client Components.
  │ To use Server Actions in a Client Component, you can either export them from a separate file with "use server" at the top, or pass them down through props from a Server Component. 

because
import {Button} from 'flowbite-react';
import {useTranslations} from 'next-intl';
import { signIn } from "@/auth"

export default function SignIn() {
    const t = useTranslations()
    return (
        <>
        <form
            action={async () => {
                "use server"
                await signIn("keycloak")
            }}
        >
            <Button type="submit" color="dark">{t('auth.sign_in')}</Button>
        </form>
        </>
    )
}

1 Reply

Oak apple gall waspOP
But even if I replace the signIn and out components to be client side...
Error: `headers` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context

components/nav/app-navbar.tsx (24:39) @ auth

  22 |     useEffect(() => {
  23 |         const getSession = async () => {
> 24 |             const session = await auth()
     |                                       ^
  25 |             setSession(session)
  26 |         }
  27 |         getSession()