Next.js Discord

Discord Forum

User authentication Nextjs 13 with supabase

Unanswered
Beveren posted this in #help-forum
Open in Discord
BeverenOP
if I wanted a particular directory of pages to require user authentication. Could I put the user auth checks in the layout.tsx file? or am I completely misunderstanding how this works, im very new to this. Thanks

10 Replies

you use middleware to check only that particular directory
if midleware is not available, then its adviced you put the "auth()" function in a cache() and put it at every page & layout of that particular directory
in layout file is fine but then when user does soft navigation, its not going to get checked again since the layout file is not rerendered
Outside layout -> inside layout: the layout is rerendered
Inside layout -> inside layout: the user is already authenticated, no need to rerender

On that note middleware doesn’t play too well with client side navigation and client side prefetching
Chinese Chongqing Dog
Why not? Doesn't it run on every route transition and before cached content?
sometimes links are prefetched and in such case, middleware is run multiple times at the same time
sometimes the user don't want to go there until for a few while but only then the session might've been expired
the part where im concerned is that if you have auth check at /dashboard and user navigates from /dashboard/a to /dashboard/b, such in the case of "Inside layout -> inside layout" form joulev's message, is that your auth check is only run at the first time but not when user access /dashboard/b. I agree that the user is already authenticated from A to B but the check is not run at B and it might be stale/expired by that time.
But then again you can also have useSession (client side checking) so it always being checked at the client side, when component is mounted. So theres also that method.