T
TanStack12mo ago
quickest-silver

Any strategy for authenticated routes as the default instead of unauthenticated?

Right now it seems suggested to use _auth/ + _auth.tsx to create protected routes (or _auth.whatever.tsx if you're doing the flat thing) which works fine but it feels a bit weird if majority of your routes are auth. There's a hypothetical situation that someone has 20 protected routes and 1 unprotected route. In this situation it would feel bad to just have one layer of nesting whether it's in a file name or nested folder for your default case. Is there a better way to do this? My brain might be fried but I can't think of anything at the moment.
5 Replies
quickest-silver
quickest-silverOP12mo ago
As an example I just want to invert this
No description
quickest-silver
quickest-silverOP12mo ago
so _unauth would have login '
unwilling-turquoise
unwilling-turquoise12mo ago
I don't think it's possible with layouts. depending on what your layouts actually do (logic or ui), it could be done by some conditional logic.
quickest-silver
quickest-silverOP12mo ago
Aw shoot. Yeah, I can definitely do it some other way but I really wanted to be able to embrace the package to do it. No worries though.
quickest-silver
quickest-silver12mo ago
Just brainstorming here, but if you really only have a couple of public routes you could just have an array of those and check them in the __root location beforeLoad and allow to pass through and otherwise do your auth check. Something like:
beforeLoad: async ({ location }) => {
const publicRoutes = ["/login"];

if (publicRoutes.includes(location.pathname)) {
return { session: null, user: null };
}
const { session, user } = await getAuthSession();

if (!user) {
throw redirect({
to: "/login",
});
}

return { session, user };
},
beforeLoad: async ({ location }) => {
const publicRoutes = ["/login"];

if (publicRoutes.includes(location.pathname)) {
return { session: null, user: null };
}
const { session, user } = await getAuthSession();

if (!user) {
throw redirect({
to: "/login",
});
}

return { session, user };
},
Now I dont know if I consider here everything or if this will even work, but I think it should

Did you find this page helpful?