Yohan Hirimuthugoda
Yohan Hirimuthugoda

Reputation: 1051

Angular SSR (Universal) Website not working with keycloak-js adapter and keycloak-angular plugin

I am strugling to translate my website to Angular SSR for better SEO ranking.

I manage to handle window, document, localStorgae calls in website.

But when I check whole site with Keycloak integration it fails due to window issue again.

I follow this post: Keycloak SSO with Angular Universal SSR, but no luck, it has typo error in the last step. It might be the reason.

Can anyone point me to the right direction.

Thank you in advanced.

Upvotes: 1

Views: 1038

Answers (1)

farad64
farad64

Reputation: 11

Facing the same problem and solved for me as follow :

I'm using a Keycloak Server (self-hosting) v21.1.1, Angular app v16.0.5. and keycloak-angular package V14.0.0

First, I've followed keycloak-angular setup : https://www.npmjs.com/package/keycloak-angular#setup and modified initializeKeycloak function like this :

declare var require: any;
const Keycloak = typeof window !== 'undefined' ? require('keycloak-js') : null;

export function initializeKeycloak(
  keycloak: KeycloakService
  ) {
    if(Keycloak!==null){
      return () =>
            keycloak.init({
              config: {
                //my config
              },
              initOptions:{
                // my options
              }
            });
    }else{
      return ()=>{
        return new Promise<Boolean>((resolve,reject)=>{
          resolve(true);
        });
      }
    }
}

Some comments :

First two lines will be used to know if 'window' exists or not (i.e. if code run in server or browser side). (found here : code for SSR but using keycloak-js)

Then, simply make an if statement on Keycloak variable (null or not) and return expected format ()=>Promise<Boolean> in both cases.

Upvotes: 1

Related Questions