Redirect unauthenticated users with meteor.js and react-router 6

The challenge I encountered was accessing the ```Meteor.user()``` in React Router's route ```loader``` property.

Alternatively, instead of querying the server, I'm picking up the user id from localStorage. The absence of it indicates the user is logged off or never logged in. Until Meteor kicks off, no sensitive data is displayed anyway. 

```
...
{
  path: '/',
  element: <App />,
  errorElement: <ErrorPage />,
  loader: async () => window.localStorage.getItem('Meteor.userId'),
}
...
```

and in ```app.tsx```:

```
const userId: UserId | null = useLoaderData()
const navigate = useNavigate()

useEffect(() => {
  if (userId === null) navigate('/login')
}, [userId])

```

Nick Ciolpan
22 Nov 2022
« Back to post