'Next.js hydration error using Keycloak SSR package

I am using @react-keycloak/ssr with latest next.js, just started so project as clean as possible, all I really have are installed dependencies and _app.tsx with index.tsx from examples.

_app.tsx is identical copy (except url to keycloak) of official github example and index.tsx is next:

import { useKeycloak } from '@react-keycloak/ssr'
import {KeycloakInstance, KeycloakTokenParsed} from 'keycloak-js'

type ParsedToken = KeycloakTokenParsed & {
  email?: string
  username?: string
}

export default function Index() {
  const { keycloak } = useKeycloak<KeycloakInstance>()
  const parsedToken: ParsedToken | undefined = keycloak?.tokenParsed
  const state = keycloak?.authenticated ? <span>{parsedToken?.username}</span> : <span>'Undefined'</span>;

  function handleLoginButtonClick() {
    if (keycloak) {
      window.location.href = keycloak.createLoginUrl()
    }
  }

  return (
    <div>
      {state}
      <button className="btn btn-blue" onClick={() => handleLoginButtonClick()}>Login</button>
    </div>
  )
}

And my problem is that after a login I am getting errors

Warning: Text content did not match. Server: "" Client: "'Undefined'"
    at span
    at div
    at Index (webpack-internal:///./pages/index.tsx:18:84)

I've tried to implement state change using useEffect but then keycloak?.authenticated is always false,

  let [state] = useState('No user');
  
  useEffect(() => {
    state = keycloak?.authenticated ? 'User' : 'No user';
  }, []);

then I tried to use getServerSideProps, but then I get an error that useKeycloak hook can be used inside a function only.

What else can I try?

p.s. Short gif/video of what is happening https://imgur.com/a/c2q6ftU



Solution 1:[1]

Found a solution by tweaking useEffect slightly:

  const [username, setUsername] = useState('unknown')

  useEffect(() => {
    if (keycloak?.authenticated) {
      setUsername(parsedToken?.email)
    }
  }, [keycloak?.authenticated])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MyMomSaysIamSpecial