Platform: “react”: “^18.2.0”
Routing Library: “react-router-dom”: “6.4.2”
Auth0 library: “@auth0/auth0-spa-js”: “^2.0.0”
Issue: getting “Error: Invalid state” when calling handleRedirectCallback
. Not sure what’s going on on the background but the login completes successfully after the error.
Setup:
Auth.js
const auth0 = new Auth0Client({
authorizationParams: {
audience: <my-audience>,
redirect_uri: <my-url>/callback,
},
cacheLocation: 'localstorage',
clientId: <my-clientId>,
domain: <my-domain>,
useRefreshTokens: true,
});
export const login = async () => {
await auth0.loginWithRedirect();
};
export const isAuthenticated = () => {
return auth0.isAuthenticated();
};
export const handleRedirectCallback = () => {
return auth0.handleRedirectCallback();
};
export const login = async () => {
await auth0.loginWithRedirect();
};
App.js
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/callback" element={<Auth0Callback />} />
<Route path="/" element={<AuthenticatedRoute component={AppLayout} />}>
// routes children of AuthenticatedRoute
</Route>
</Routes>
Auth0Callback.js
export default function Auth0Callback() {
const navigate = useNavigate();
useEffect(() => {
(async () => {
try {
await handleRedirectCallback();
navigate(localStorage.getItem('redirectTo') || '/');
} catch (e) {
console.log('e', e); // ERROR IS LOGGED HERE
}
})();
}, [navigate]);
return (
<SpinnerContainer>
<Spinner />
</SpinnerContainer>
);
}
AuthenticatedRoute.js
export const AuthenticatedRoute = ({ component: Component }) => {
const location = useLocation();
const [authenticated, setAuthenticated] = useState(false);
useEffect(() => {
(async () => {
const authenticated = await isAuthenticated();
setAuthenticated(authenticated);
if (!authenticated) {
localStorage.setItem('redirectTo', location.pathname);
login();
}
})();
return;
}, [location.pathname]);
return authenticated ? (
<Component />
) : (
<SpinnerContainer>
<Spinner />
</SpinnerContainer>
);
};
export default AuthenticatedRoute;