SolidJSS
SolidJSโ€ข2y agoโ€ข
1 reply
GGboi.eth

Pass authed user data to protected routes

I am trying to pass validated data to protected routes so I don't have to check undefined. Routes are currently protected with RouteGuard which redirects to the sign in page if there is no user.

If there is a user, I want to pass the validated data to all nested routes without having to manually pass the data to each route or setup a context provider for each route.


const RouteGuard: ParentComponent = (props) => {
  const user = true; //Fetch User
  const navigate = useNavigate();
  if (!user) {
    navigate("/auth/sign-in");
  }
  return (
      <>{props.children}</>
  );
};

const AuthWrapper: ParentComponent = (props) => (
  <AuthProvider>{props.children}</AuthProvider>
);

const App: Component = () => {
  return (
    <Router>
      <Route path="/auth" component={AuthLayout}>
        <Route path="sign-in" component={SignInUp} />
      </Route>
        <Route path="/" component={RouteGuard}>
          <Route path="/home"  component={() => <AuthWrapper><Home/></AuthWrapper>} />
        </Route>
    </Router>
  );
};


The example above shows the
/home
route receiving the user props throught the AuthWrapper component. But I would need to do that for every route.

Is there some equivalent to this?
const App: Component = () => {
  return (
    <Router>
      <Route path="/auth" component={AuthLayout}>
        <Route path="sign-in" component={SignInUp} />
      </Route>
      <Route path="/" component={RouteGuard}>
        <AuthWrapper>
          {/* All routes in here can access the validated user data */}
          <Route path="/home" component={Home} />
        </AuthWrapper>
      </Route>
    </Router>
  );


Also, I plan on using solid-query as the async state manager so it would be great if the solution could just use the user response from RouteGuard. This would just be a bonus though
Was this page helpful?