score:4

Short summary of one possible solution:

  1. Wrap all routes that require authentication inside <ProtectedRoute> component that redirects unauthenticated users to login page. ProtectedRoute-component just check if user has valid token, if not redirects user.
  2. Inside error link first remove token, or somehow unvalidate it, then call location.reload()

Detailed implementation below.

I was not able to find any straightforward solution. In normal cases, to redirect user I use react-router navigate() hook. Inside the error link I found no way to use react-hooks.

However, I managed to solve the actual problem. I implemented ProtectedRoute component which wraps all the parts of the application which requires authentication:

type ProtectedRouteProps = {
    path: string;
    toRedirect: string;
};

export const ProtectedRoute: FunctionComponent<ProtectedRouteProps> = ({
    path,
    toRedirect,
    children,
}) => {
    return isAuthenticated() ? (
        <Route path={path}>
            {children}
        </Route>
    ) : (
        <Navigate to={{ pathname: toRedirect }} />
    );
};

type ValidToken = string;
type ExpiredToken = 'Expired token'
type NullToken = '' | null

export type JwtTokenType = (ValidToken | ExpiredToken | NullToken )
export const isNullToken = (token: JwtTokenType) : boolean => {
    return (token === '' || token === null)
}

export const isExpiredToken = (token: JwtTokenType) : boolean => {
    return token === "Expired token"
}

export const isAuthenticated = () : boolean => {
    let token = getTokenFromCookies();
    return !(isExpiredToken(token) || isNullToken(token));
}

I use it as follows:

<Routes>
   <Route path="login" element={<LoginPage />} />
   <ProtectedRoute path="/*" toRedirect="login">
      // protected routes here
   </ProtectedRoute>
</Routes>

To handle logouts and redirects for unauthenticated user I implemented two functions:

// Use this in normal cases
export function useHandleLogout(): () => void {
    const navigate = useNavigate();
    // maybe call other hooks
    });
    function handleLogout() {
        navigate("/login");
        removeToken();
        // do other stuff you want
    }
    return handleLogout;
}

// Use this inside error-link
export const handleLogoutWithoutHook = () => {
    // Logout without hook
    removeToken();
    // do other stuff required when logout
    // eslint-disable-next-line no-restricted-globals
    location.reload();
    // location.reload() after token removed affects user redirect
    // when component is wrapped inside <ProtectedRoute> component

};

export const removeToken = () => {
    Cookies.remove("jwt-token")
}

And finally inside the error link:

export const errorLink =  onError(
    ({ graphQLErrors, networkError, operation, forward }) => {
        if (graphQLErrors) {
            for (let err of graphQLErrors) {
                if (err.message.includes('AnonymousUser')) {
                    handleLogoutWithoutHook()
                    return
                }
                if (err.message.includes('Signature has expired')) {
                    handleLogoutWithoutHook()
                }
                console.log(err.message)
            }
        }
        return forward(operation)
    }
);

Related Query

More Query from same tag