App Router Conditional Slots for Authentication
Unanswered
Western thatching ant posted this in #help-forum
Western thatching antOP
Hi, would like advice on using conditional rendering with parallel routes, for implementing user login and authentication. The solution I currently have (which seems to basically work) is structured this way:
/app/layout.tsx:
The goals here are:
- unauthenticated user sees the login view for any request, without being redirected
- unauthenticated user cannot extract information about the system based responses (catchAll route treats all requests equally)
- after successful auth, the session cookie is set and the page re-renders to the user's destination (or 404)
Issues:
1. can't currently make an optional catchall route work (
2. a non-existent page throws an annoying warning in the console like
Neither of these issues is a dealbreaker, and it does basically work. But I wanted to solicit advice on whether this is a sound design, or if it could be done better.
/app/default.tsx
/app/layout.tsx
/app/@authenticated/layout.tsx
/app/@authenticated/page.tsx
/app/@login/[...catchAll]/page.tsx
/app/@login/layout.tsx
/app/@login/page.tsx/app/layout.tsx:
type RootLayoutProps = PropsWithChildren<{
authenticated: React.ReactNode;
login: React.ReactNode;
}>;
export default async function RootLayout({
authenticated,
children,
login,
}: RootLayoutProps) {
const session = await getSession();
return (
<html lang="en">
<body>
{children}
{session ? authenticated : login}
</body>
</html>
);
}The goals here are:
- unauthenticated user sees the login view for any request, without being redirected
- unauthenticated user cannot extract information about the system based responses (catchAll route treats all requests equally)
- after successful auth, the session cookie is set and the page re-renders to the user's destination (or 404)
Issues:
1. can't currently make an optional catchall route work (
/app/@login/[[...catchAll]]/page.tsx), so the extra /app/@login/page.tsx is required, which returns null2. a non-existent page throws an annoying warning in the console like
"No default component was found for a parallel route rendered on this page. Falling back to nearest NotFound boundary.", but I can't add a default.tsx or the design falls apartNeither of these issues is a dealbreaker, and it does basically work. But I wanted to solicit advice on whether this is a sound design, or if it could be done better.