I was wondering how to exactly implement authentication flow with React Router if my app is rendering server-side?
The scenario:
When the user first arrives at the app, we invoke an onEnter
router method in order to check if any current user is present (localStorage
), if they are we will redirect them to their dashboard, otherwise we redirect them to the landing page.
Therefore when my app hits my protected routes onEnter
, here's ideally what should happen:
onEnter: () => {
if (localStorage.getItem('authToken')) {
// Authenticate and redirect user to intended path
} else {
// Redirect the user to the login page
}
}
The problem here is that because we're rendering server-side, we don't have access to things such as localStorage
. Can anyone suggest a way to overcome this, or a better way to handle server-side auth with React Router?
You could use context, e.g:
And wrap:
You can then access it on the server or client from any component:
Simple client check something like
typeof document !== 'undefined'