Ad

React-router Auto-login In The OnEnter Hook

- 1 answer

In all the react-router examples for the onEnter hook, the hook is synchronous. In the issues it's recommended to keep it that way. What's the idiomatic way to log someone in while inside a hook?

User-story:

  1. Client has a localStore token
  2. Client navigates directly to example.com/mustBeLoggedIn
  3. Before going to that page, I'd like to check if they have a token, if they do, attempt to gain authorization. If authorized, continue onto route

Should I just use a HOC instead of onEnter?

I currently have it working, but I know it's not recommended, and seems very brittle, for example using an immutable store causes the same issues as this issue: https://github.com/rackt/react-router/issues/2365

Ad

Answer

There are a number of ways to solve this challenge, but I agree with the recommendation that calls in onEnter should be synchronous. Here are two ways to solve this challenge.

Option 1: Don't Validate the Token on Page Load

It is arguably the case that the browser should not validate the existing token at all. That is, the browser should assume that the token is valid and try to load the route as defined.

On an API call failure response from the server (where the actual authentication and authorization is really occurring), your app can handle the need to re-authenticate any way it chooses: redirect to a login page, present a login dialog, etc.

The advantage of this approach is that it will work across all routes that employ this logic without having to specify the routes that need it individually.

Option 2: Use an HOC (recommended)

As you suspected, an HOC is probably the best way to go. Your router would attempt to render something like this:

<EnsureAuthorized checks={myCheckFunction} Component={MustBeLoggedIn} />

This kind of flexible HOC could optionally run custom authorization checks in addition to the required authentication checks (like user roles), and render the component provided only when the authentication and the checks succeed, and then handle failures in a consistent way (e.g. rendering a login component or redirecting the user to the login page or showing a 403-type message, etc).

Ad
source: stackoverflow.com
Ad