React with keycloak js adapter and react-keycloak binding resulting in an endless loop

  javascript, keycloak, reactjs

So I’ve just created a new React project where I use the official keycloak-js adapter with the react-keycloak/web dependency for react bindings. I have followed all the "official" ways of doing things and I have this:

keycloak.js (config):

import Keycloak from "keycloak-js";

// Setup Keycloak instance as needed
const keycloak = new Keycloak({
    realm: "SomeRealm",
    url: process.env.REACT_APP_KEYCLOAK_URL + "/auth/",
    clientId: "app-id",
});

export default keycloak;

The index file looks like this:

// Keycloak
import { ReactKeycloakProvider } from "@react-keycloak/web";
import keycloak from "./keycloak";

const keycloakProviderInitConfig = {
  onLoad: "login-required",
};

ReactDOM.render(
  <ReactKeycloakProvider
    authClient={keycloak}
    initOptions={keycloakProviderInitConfig}
  >
    <React.StrictMode>
      <ChakraProvider>
        <App />
      </ChakraProvider>
    </React.StrictMode>
  </ReactKeycloakProvider>,
  document.getElementById("root")
);

So this "should" redirect the user to login if he is not authenticated, but instead, the content off the page is rendered. So i tried an alternative implementation of conditionally showing the content with this snippet:

useEffect(() => {
    if (!keycloak.authenticated) {
      keycloak.login();
    }
  }, [keycloak]);

  return keycloak.authenticated ? (
    <>
      <Navbar />
      <SomeContent />
    </>
  ) : null;

But that results in an endless loop if the user is authenticated.

Any help would be appreciated 🙂

versions:

"@react-keycloak/web": "^3.4.0",
"keycloak-js": "^12.0.3"

Source: Ask Javascript Questions

One Reply to “React with keycloak js adapter and react-keycloak binding resulting in an endless loop”

LEAVE A COMMENT