TanStackT
TanStack2y ago
2 replies
endless-jade

Style/Best Practices

I've got a question about styling/best practice for a layout like component.

The code below is how I have the root.tsx setup at the moment, I'm using session storage to hold tokens then checking if a user has permission to get past the login view. And if they do the root renders the navbar that will be rendered in all routes, kind of like a layout, (at least how I understand them).

const RootComponent = () => {
    const { isAuthenticated } = Route.useRouteContext();

    return (
        <>
            {isAuthenticated && <NavBar />}
            <Container maxWidth="xl">
                <Outlet />
            </Container>
        </>
    );
};

export const Route = createRootRouteWithContext<CustomRouterContext>()({
    component: RootComponent,
    beforeLoad: ({ location, context }) => {
        const { isAuthenticated } = getSession();
        // If the user is logged out, redirect them to the login page
        if (!isAuthenticated && location.pathname !== '/login') {
            throw redirect({
                to: '/login',
                search: {
                    redirect: location.href,
                },
            });
        } else if (isAuthenticated) {
            return { ...context, isAuthenticated };
        }
    },
});


I have another branch where I changed this to use a _layout.tsx and _layout dir where all routes that require auth live in, and the
root.tsx just renders a outlet. But this also means every route has changed, the app is currently in use, so having every route change doesn't feel good, and I'm having to manually test to make matters worse.

My personal opinion is that using a layout, and calling it auth and having all routes that require it live in the dir and use a _auth.tsx layout for rendering the navbar and container is the right way. But I'm getting push back due to all the routes changing and it feeling I guess like overkill.

I was wondering what you guys think?
Was this page helpful?