Meteor React Starter code(React Routing Divided Private and Public Routes)

Hey guys!

I want to quickly ask the Meteor Community if you guys have recommended a Github repo that has Meteor React Starter code for me to check how others implement React Routing (the latest one) and how they do Authenticated Routes and Public Routes divided. I want to quickly check on how others implement it or if you have ideas other than React Router. Thanks!

  • Steven

I can’t share publicly, but my approach is simple. I’m using react-router and I have three special route components that check if the user is logged in (component 1), is not logged in (component 2) or if is user with a specific permission (component 3). If the condition is false I redirect either to login or to user dashboard.

1 Like

I can definitely add it here next time I’m at the computer.

Feel free to email me if I don’t (filipe@quave.dev)

2 Likes

Looking forward to it. Thanks!

I am trying to imagine this but thanks for the effort. :slightly_smiling_face:

Hi Steven, I just push code with conditional routing into quave’s template.

I’ve tried to provide a complete example covering 3 cases:

  • Pages for authenticated people only (LoggedLayout)
  • Pages for anonymous people only (AnonymousLayout)
  • Pages for all people (PublicLayout)

See that I’m redirecting the user using Navigate when it goes to the “wrong state” but you could also show an error message.

The main intuition in latest React Router is to control the access level not in the route itself but inside the component this is why I’m using this concept of Layouts :wink:

2 Likes

I have a different approach. I created a SecureRoute component:

import React, { lazy, useContext } from 'react'
import { Route } from 'react-router-dom'

import { AccountContext } from '/imports/ui/contexts/account-context.js'

const NotAuthorized = lazy(() => import('/imports/ui/components/not-authorized.js'))
const Login = lazy(() => import('/imports/ui/components/account/login.js'))

export default function SecureRoute({ roles, ...rest }) {
  const { isLoggedIn, loading } = useContext(AccountContext)
  const hasRights = roles ? Roles.userIsInRole(Meteor.userId(), roles) : true
  if (isLoggedIn && hasRights) {
    return <Route {...rest} />
  } else if (isLoggedIn && !hasRights) {
    return <NotAuthorized />
  } else if (!loading && !isLoggedIn) {
    return <Login />
  }
  return <></>
}

Then we can define the routes like this:

<Suspense fallback={<Loading loading />}>
      <Switch>
        <SecureRoute roles={['ADM']} path="/admin" component={AdminPage} />
        <Route path="/login" exact component={Login} />
      </Switch>
</Suspense>
1 Like