DEV Community

Venkata Ravindra
Venkata Ravindra

Posted on

Keycloak authentication with your Next.js

  1. Install the required packages:
npm install next-auth keycloak-js
Enter fullscreen mode Exit fullscreen mode
  1. Create a pages/_app.js file with the following code:
import { Provider } from 'next-auth/client';
import { useEffect } from 'react';
import Keycloak from 'keycloak-js';

function MyApp({ Component, pageProps }) {
  useEffect(() => {
    const keycloakConfig = {
      url: 'YOUR_KEYCLOAK_URL',
      realm: 'YOUR_REALM',
      clientId: 'YOUR_CLIENT_ID',
    };

    const keycloak = Keycloak(keycloakConfig);

    keycloak.init({ onLoad: 'login-required' }).success((authenticated) => {
      if (authenticated) {
        // If the user is authenticated, render the app
        keycloak.loadUserProfile().success((userProfile) => {
          // Pass the user's profile to the app
          pageProps.user = userProfile;
          renderApp();
        });
      } else {
        // If the user is not authenticated, redirect to Keycloak login
        keycloak.login();
      }
    });

    function renderApp() {
      ReactDOM.render(
        <Provider session={pageProps.session}>
          <Component {...pageProps} />
        </Provider>,
        document.getElementById('root')
      );
    }

    return () => {
      ReactDOM.unmountComponentAtNode(document.getElementById('root'));
    };
  }, []);

  return null;
}

export default MyApp;
Enter fullscreen mode Exit fullscreen mode
  1. In your Next.js pages, you can access the user's profile using useSession from next-auth/client. For example, in pages/index.js:
import { useSession } from 'next-auth/client';

export default function Home() {
  const [session, loading] = useSession();

  if (loading) {
    return <div>Loading...</div>;
  }

  if (!session) {
    return null; // Redirecting to Keycloak login
  }

  return (
    <div>
      <h1>Welcome, {session.user.name}!</h1>
      <button onClick={() => signOut()}>Sign Out</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Make sure to replace the placeholders YOUR_KEYCLOAK_URL, YOUR_REALM, and YOUR_CLIENT_ID with your actual

Top comments (1)