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',
},
});
}
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
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);
});
}
}
}