@elyash14/next-keycloak

An authentication library based on Keycloak for NextJs applications

Usage no npm install needed!

<script type="module">
  import elyash14NextKeycloak from 'https://cdn.skypack.dev/@elyash14/next-keycloak';
</script>

README

Next Keycloak

An authentication library based on Keycloak for NextJs applications

Next Keycloak powerd by Typescript, React and keycloak Use it as a react provider to authenticate keycloak users

NPM version

Features

  • Support Keycloak public client
  • Access user information and token in both client & server side

Requirements

  • Keycloak.js version 11 or above
  • React version 16 or above
  • NextJs version 10 or above

Installation

Install package with this command

npm i @elyash14/next-keycloak
or
yarn add @elyash14/next-keycloak

Make a config file in _app.tsx or _app.jsx and wrap your component with NextKeycloakAuthProvider like this:

const config:KeycloakConfig = {
  realm: process.env.NEXT_PUBLIC_KEYCLOAK_REAM,
  url: process.env.NEXT_PUBLIC_KEYCLOAK_URL,
  clientId: process.env.NEXT_PUBLIC_KEYCLOAK_CLIENT_ID,
};

const initOption :KeycloakInitOptions = {
  onLoad: 'check-sso',
  silentCheckSsoRedirectUri:
    'http://localhost:3000/silent-check-sso.html',
}

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <NextKeycloakAuthProvider config={config} initOption={initOption}>
      <Component {...pageProps} />
     </NextKeycloakAuthProvider>
  );
}
export default MyApp;

Also you can provide initialOption based on keycloak documentation and pass it to the provider. Note that the above example supports "silent check sso" and needs an HTML in your public folder. Create the silent-check-sso.html file in the public folder and put the below content into it.

<html>
<body>
    <script>
        parent.postMessage(location.href, location.origin)
    </script>
</body>
</html>

And that's it... now you can use useNextKeycloakAuth in your pages and components like this:

const {authenticated, loading } = useNextKeycloakAuth();

See this example for full example.

Authors

Elyas Mosayebi @elyash14

License

MIT