Search code examples
next.jsnext-authnext.js14

NextAuth global useSession


)

I am using the Next.js v.14 with next-auth v.4.24.

I am following the documentation and so I am using the "SessionProvider" wrapped in the layout.

When using it inside a page or a component e.g. "Header" it needs to be turned in to a client side with the "use client" and importing the "useSession".

I am trying to avoid turning every page into a client just to check if session exists or not. Usually I create a client components e.g. "themeToggle" and then import it into a page (server side). Would it be possible to do the same with the importing of the "useSession" or i must convert it all into a server side?

btw... in the nextauth route i'm using the jwt as the session strategy.

any help of a short code would be very appreciated!


Solution

  • You can use getServerSession or in v5 auth in your server components.

    If you use this in your root layout, you can forward the session down into other components using prop drilling and then provide to any session provider with <SessionProvider session={session}>.

    However, with server actions, there is little reason to keep track of your session on the client side anymore. I would recommend to primarily use it on the server and provide it to the client as props where necessary.