Using guard condition in layout.tsx
Unanswered
Oriental posted this in #help-forum
OrientalOP
I am attempting to use a guard pattern in
But this doesn't work too well, if there is a child page assuming that the user is signed-in, it will throw an error since in RSC
Note:
Why I am not using
layout.tsx
, e.g.export default async function MainLayout(props: { children: ReactNode }) {
const authState = await getAuthState(); // not necessarily an authentication guard, just as an example
if (!authState) {
redirect("/signin");
}
return props.children;
}
But this doesn't work too well, if there is a child page assuming that the user is signed-in, it will throw an error since in RSC
children
is rendered before being passed to the layout. Are there better patterns of having guards in layouts?Note:
Why I am not using
middleware.ts
: I also want to co-locate the code (imagine I have several of these checks and each of them have different children, it would be a nightmare to manage).3 Replies
Asian black bear
You shouldn't use layouts for auth checks in the first place since they don't rerender on navigation.
The safe way is a combination of middleware and checks in pages / route handlers.
Don't make assumptions that the user is logged in.