react-router-guards icon indicating copy to clipboard operation
react-router-guards copied to clipboard

Resolve infinite redirects, broken redirects for same paths with different params

Open joshpensky opened this issue 3 years ago • 0 comments

Description

In our render resolution of Guard, we included a method to resolve redirecting to the same path.

Unfortunately, this didn't actually account for a redirect to the same path with different parameters. To fix this, we now perform a check for infinite redirection and only perform redirects in the render

Related issues

Fixes #55

What this does

  • Adds a check for infinite renders in validateRoute and throws up an error if so
  • Removes path checking in routeRedirect case of render—now only renders the Redirect component
  • Update default error from 'Not found.' to rrg/error (to match other errors)

How to test

Following the example in #55:

  1. Pull down the repo locally and set up the dev server (npm i, npm run bootstrap, npm start)

  2. In src/router/index.tsx, add the following guard function:

const invalidName: GuardFunction = (to, from, next) => {
  const { name } = to.match.params;
  if (name === 'test') {
    next.redirect('/charmander');
  } else {
    next();
  }
};
  <GuardedRoute
    path="/:name"
    exact
    component={Detail}
-   guards={[waitOneSecond, detailBeforeEnter]}
+   guards={[invalidName, waitOneSecond, detailBeforeEnter]}
  />
  1. Visit http://localhost:3001/test. Confirm the redirect resolves correctly to /charmander
  2. Update the invalidName guard to cause an infinite redirect to /test
  3. Confirm the app doesn't infinitely redirect + break, but rather throws up an error page

Additional Notes

Currently the routes are only "matched" by their pathname—something that will be changed by #39 (or similar functionality changes from that)

joshpensky avatar Sep 13 '21 20:09 joshpensky