What's the best way to check authentication? Can I check the session once in a Next.js layout?

I'm currently importing the auth client, getting the session, and checking if it exists. If not, the user is redirected to the landing page:
const session = await auth.api.getSession({ headers: await headers() });

if (!session) {
redirect("/");
}
const session = await auth.api.getSession({ headers: await headers() });

if (!session) {
redirect("/");
}
I understand that this check is needed on every page for proper authentication. But I'm using React + Next.js and already have the check in a layout, so I wonder if that alone is enough to avoid repeating it. My guess is yes, but I'm not very experienced with Next.js. If it works with just the layout, what’s the best way to give components access to the session (user ID, name, email, etc.)? Otherwise, I’d have to redo the check in each component that need the session. I looked into alternatives, like passing the session as a prop, using a context provider, or storing it in a lib, but they seem more complicated than simply importing the auth client again. They don’t seem worth it for the minor abstraction they provide.
Solution:
Right there is no way of hydrating the session on the layout but will be working on it for sure. Till then each of the page tree needs to fetch check on auth state is they don’t have ancestral relationship
Jump to solution
2 Replies
Solution
KiNFiSH
KiNFiSH4w ago
Right there is no way of hydrating the session on the layout but will be working on it for sure. Till then each of the page tree needs to fetch check on auth state is they don’t have ancestral relationship
Bigrand 🇨🇴
Bigrand 🇨🇴OP4w ago
Thank you for the answer!

Did you find this page helpful?