Skip to content

How can I make protected routes? #359

Answered by molefrog
abcd-arl asked this question in Q&A
Discussion options

You must be logged in to vote

I guess it is similar to how you would implement protected routes with any other router. Generally, what you need is:

  • Keep the track of the currently authenticated user somewhere that can be accessed in any component of your app (in a context, or with your state management of choice).
  • Write a wrapper component e.g. <ProtectedRoute>...</ProtectedRoute> that will (pseudo-code):
const RequireAuth(props) => {
  const [location] = useLocation();
  const user = useCurrentUser();

  const isProtectedRoute = ... // assert that `location` matches the protected area, you can compare strings, use regexps or use `useRoute` from wouter

  if (isProtectedRoute && !user) {
    return <Redirect to="/auth"

Replies: 3 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@abcd-arl
Comment options

Answer selected by abcd-arl
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants