Keycloak-js and react-relay environment; undefined when importing keycloak instance for token

So let me start off that I am not a JS expert so forgive me if the problem is simple.

We are attempting to integrate keycloak in a react frontend and graphql backend using keycloak-react/web, keycloak-js, and react-relay.

The index.js of the frontend looks as such:

import { KeycloakProvider } from ‘@react-keycloak/web’;
import keycloakInst from ‘./keycloak’;

const onKeycloakEvent = (event, error) => {
console.log(‘onKeycloakEvent’, event, error);

const onKeycloakTokens = (tokens) => {
// localStorage.setItem(‘token’, tokens.token);
console.log(‘onKeycloakTokens’, tokens);

onLoad: ‘login-required’,
checkLoginIframe: false,
enableLogging: true,

, document.getElementById(‘root’),

The keycloak.js file:

import Keycloak from ‘keycloak-js’;

const config = {
realm: process.env.REACT_APP_KEYCLOAK_REALM || ‘’,
url: process.env.REACT_APP_KEYCLOAK_URL || ‘’,
clientId: process.env.REACT_APP_KEYCLOAK_CLIENT_ID || ‘’,

const keycloakInst = Keycloak(config);
keycloakInst.redirectUri = ‘http://localhost:3000/login’;

export default keycloakInst;

And finally the RelayNetworkLayer:

import keycloakInst from ‘…/keycloak’;

const getToken = () => {
console.log(‘Heeerrrrres token!’);
return keycloakInst.authenticated ? keycloakInst.token : ‘’;

const network = new RelayNetworkLayer(
url: ${APP_BASE_PATH}/graphql,
credentials: ‘same-origin’,
token: getToken(),
allowEmptyToken: true,
{ subscribeFn },

The issue is that when the login is successful in keycloak, and the first request to the graphql backend is made, the getToken() method is called and keycloakInst is undefined as well as the token. The print statements in the index.js print the tokens upon success.

To get more output, I added some simple checks in the Login component to display the token:

const { keycloak, initialized } = useKeycloak();
if (keycloak.authenticated) {
return (

authed {keycloak.token}

return (
Working on it


When the login is successful, the token is displayed in the div as expected. But the import in the environment is always undefined. Is there some threading or import stuff I might not understand as to why the keycloakInst import is always undefined?