roconmachine
roconmachine

Reputation: 2126

document is not defined while initialize keycloak service

I am developing angular application where keycloak require to integrate. i use angular 18 and keycloak.ja 24.0.2 version.

Here is the code where keycloak service initiates.

import Keycloak from 'keycloak-js';
import { KeycloakService } from 'keycloak-angular';

export function initializeKeycloak(keycloak: KeycloakService): () => Promise<boolean> 
{
  return (): Promise<boolean> =>
  keycloak.init({
  config: {
    url: 'http://localhost:8080/auth',
    realm: 'MyRealm',
    clientId: 'angular-app',
  },
  initOptions: {
    onLoad: 'login-required',
  },
});
}

Error occured when keycloak try to initialize

For reference this is app.config

export const appConfig: ApplicationConfig = {
 providers: 
  [provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes), 
  provideClientHydration(), KeycloakService,
 {
  provide: APP_INITIALIZER,
  useFactory: initializeKeycloak,
  multi: true,
  deps: [KeycloakService]
  }
 ]

};

Advanced thanks

Upvotes: 1

Views: 159

Answers (1)

Naren Murali
Naren Murali

Reputation: 57986

As per this github issue you need to wrap the init inside a if condition and execute it only when keycloak ( along with document and window ) is present (only on browser and not on the server).

import Keycloak from 'keycloak-js';
import { KeycloakService } from 'keycloak-angular';

export function initializeKeycloak(keycloak: KeycloakService): () => Promise<boolean> 
{
  return (): Promise<boolean> => {
    if(typeof window !== 'undefined') {
      return keycloak.init({
        config: {
          url: 'http://localhost:8080/auth',
          realm: 'MyRealm',
          clientId: 'angular-app',
        },
        initOptions: {
          onLoad: 'login-required',
        },
      });
    } else {
        return new Promise<Boolean>((resolve, reject) => {
          resolve(true);
        });
    }
  }
}

Upvotes: 1

Related Questions