Search code examples
reactjstypescriptkeycloak

React Keycloak Implementation - Can only be instantiated once


Because it didnt worked in my main application, i created a new raw react project and implemented the simple keycloak login there following the documentation: https://github.com/react-keycloak/react-keycloak/blob/master/packages/web/README.md

Now i get the following Error, that a Keycloak Instance can only be instantiated once.

Browser-Console Error stack

App.tsx Code:

import './App.css'

import { ReactKeycloakProvider } from '@react-keycloak/web'
import keycloak from './keycloak'

function App() {

  return (
    <>
      <ReactKeycloakProvider authClient={keycloak}>...</ReactKeycloakProvider>
    </>
  )
}

export default App

keycloak.ts Code:

import Keycloak from 'keycloak-js'

const initOptions = {
    url: 'http://0.0.0.0:8080/auth',
    realm: 'test',
    clientId: 'test_client'
}

const keycloak = new Keycloak(initOptions)

export default keycloak

I tried different approaches and even asked ChatGPT but nothing helped. I also read similar questions from stackoverflow but none of the solutions helped.

I tried to do a singleton pattern class for the keycloak instance but this also didnt work.

class KeycloakConfiguration {
private static instance: Keycloak.KeycloakInstance | null = null

private constructor() {}

public static getInstance(): Keycloak.KeycloakInstance {
    if (!KeycloakConfiguration.instance) {
        const initOptions = {
            url: 'http://0.0.0.0:8080/auth',
            realm: 'test',
            clientId: 'test_client',
        }

        KeycloakConfiguration.instance = new Keycloak(initOptions)
    }

    return KeycloakConfiguration.instance
}

}


Solution

  • I found out what the error was. The Application was wrapped in <React.StrictMode> which caused the application to render twice. After i removed the StrictMode Item, the Error disappeared

    ReactDOM.createRoot(document.getElementById('root')!).render(
        <React.StrictMode>
            <BrowserRouter>
                <ReactKeycloakProvider authClient={keycloak}>
                    <App />
                </ReactKeycloakProvider>
            </BrowserRouter>
        </React.StrictMode>
    )