Next.js Discord

Discord Forum

Auth protection in nextjs

Unanswered
Giant Chinchilla posted this in #help-forum
Open in Discord
Giant ChinchillaOP
hi , i need some help in routing protection in nextjs basically we store data after signup or login in local storage using nextauth and then i am got confuse should i make one authguard component and use it on every layout?
or i also find middleware way but there i am unable to access localstorage because that run on server side how i handle i got confuse. basically i want redirect to user specific route based on role?

3 Replies

@Giant Chinchilla hi , i need some help in routing protection in nextjs basically we store data after signup or login in local storage using nextauth and then i am got confuse should i make one authguard component and use it on every layout? or i also find middleware way but there i am unable to access localstorage because that run on server side how i handle i got confuse. basically i want redirect to user specific route based on role?
you shouldn't check your auth inside your layout. The client will be able to see the protected content. For more about that see here: https://github.com/eric-burel/securing-rsc-layout-leak

Next-auth provides a way to access the session also serverside in edge env. like this:
const session = await getToken({ req: request });

Like that you can redirect or do something else with the client. The middleware itself can than match only protected routes
@Giant Chinchilla solved?
Giant ChinchillaOP
Hi @B33fb0n3! The issue is resolved, but I'm feeling a bit confused about managing state. I’m familiar with Redux, but with the new React Server Components (RSC) behavior, I'm not sure how to proceed. I haven’t found much information online about state management in Next.js either. Any advice would be appreciated!