Cant use the blessed approach just yet? A quick way to solve browser redirects after auth using react-router

By: John Detlefs
Posted: November 25, 2019

Kent Dodds delineates a pretty good approach to auth in a react app here, https://kentcdodds.com/blog/authentication-in-react-applications.

If you're using react-router and useContext in your app just auth that way. Its very convenient to have AuthenticatedApp and UnauthenticatedApp as the sides of your ternary in that authentication check.

If for some reason you cant get this in as a ticket and you need to solve redirects quickly in an additive fashion (very little refactoring necessary) use location.state! Location state lets us pass data on a router action like history.push.

Assuming you already have redirecting unauthenticated users to an unauthenticated view, the method of fixing bad redirects generalizes to two parts

  1. Find the react router redirect to prop or history.push action that is causing that redirect and refactor it to this.

Before

<Redirect to='login' /> (could also be) /> or thishistory.push({pathname: 'login', state: { redirectPathName: pathname, redirectSearchParams: search})

After

const { pathname, search } = useLocation()
// in route declaration
<Redirect to={{pathname: 'login', state: { redirectPathName: pathname, redirectSearchParams: search}} />

  1. Find the login method that pushes to the new authenticated route.

Before

handleLogin(username, password) {
   const { push } = useHistory();
   // handle login stuff
   // onSuccess do this
   push('/')
}
   

After

handleLogin(username, password) {
   const { push } = useHistory();
   const { state } = useLocation();
   // handle login stuff
   // onSuccess do this
   push(state.redirectPathname ?  { pathname: state.redirectPathName, search: state.redirectSearchParams ?? '' }  : '/')
}