Next.js Discord

Discord Forum

Root layout with async action Is a good approach?

Unanswered
porto posted this in #help-forum
Open in Discord
Guys, I'm developing a portfolio website that uses next-auth only on book-guest page. In a first moment I've put the SessionProvider directly on root layout. Something like this:

import { NextAuthWithClientRendering } from '@providers/auth'
import { getServerSession } from 'next-auth'

export default async function Layout({ children }: TSStuff) {
  const session = getServerSession()
  
  return (
    <NextAuthWithClientRendering session={session}>
      {...}
    </NextAuthWithClientRendering>
  )
}


But, during build time I've noticed that I was not be able to generate static, every pages was SSR. So I've decided to make some tests. First was removing the getServerSession() of Layout (turn it sync)

import { NextAuthWithClientRendering } from '@providers/auth'
import { getServerSession } from 'next-auth'

export default async function Layout({ children }: TSStuff) {
  
  return (
    <NextAuthWithClientRendering>
      {...}
    </NextAuthWithClientRendering>
  )
}


The only thing that it causes is that I need to but some Suspenses or loading.tsx files in some routes. The auth functionally did still working without any problem, so my first question is. What is the point of getServerSession()?


My second approach was:
1. Create a layout page to guest-book routes
2. Move the <NextAuthWithClientRendering /> to this layout, keeping the getServerSession and session prop.

This approach worked to... So which one is the recommended? I'm mean, looks like scope NextAuth only in required pages is a great thing, considering that it was wrapping a range of unnecessary routes (routes that don't even use it). But I haven't got the point of using getServerSession() considering that it haven't affect the behaviour.

1 Reply

If you want to see how is the seccond approach in the real code, just check the following pr: https://github.com/dpnunez/portfolio/pull/69