Next.js Discord

Discord Forum

documentation confusing regarding auth and layout

Answered
French Lop posted this in #help-forum
Open in Discord
French LopOP
In this page of the documentation regarding authentication with App Router:
https://nextjs.org/docs/app/guides/authentication#layouts-and-auth-checks
the documentation states that

- we should not verify sessions in the layout
- sessions should be verified "close to your data source or component ..."

The sections also shows the following sample code:

// app/layout.tsx
export default async function Layout({
  children,
}: {
  children: React.ReactNode;
}) {
  const user = await getUser();
 
  return (
    // ...
  )
}


// app/lib/dal.ts
export const getUser = cache(async () => {
  const session = await verifySession()
  if (!session) return null
 
  // Get user ID from session and fetch data
})


... which to me, looks like verifying session in the layout. The sample code seems to be contradicting the explanation, and I am confused how to actually so user information in layout components like sidebars and headers.

How do I comprehend this?
Answered by joulev
if you need to render user specific data in the layout then fetch that data in the layout. if you don't need to render user specific data in the layout then don't fetch that data in the layout.

the point is, if you already fetch user data in the layout, you still cannot assume the page is protected because it isn't.
View full answer

5 Replies

Cicada killer
I agree, it seems contradictory
Don't do an auth check in the layout... instead, do an auth check in the layout
Answer
French LopOP
ah ok. so in the case when I need to display user info in the layout, i need to

- get the user in layout,
- and also get the user in each page

i now see why the docs had cache in the sample code. thank you!