DEV Community

John Detlefs
John Detlefs

Posted on

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

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 ?? '' }  : '/')
}

Top comments (2)

Collapse
 
dance2die profile image
Sung M. Kim

Hi John, KCD's article seems to be missing s at the end.

kentcdodds.com/blog/authentication...

Collapse
 
jdetle profile image
John Detlefs

thanks!