DEV Community

Venkata Ravindra
Venkata Ravindra

Posted on

middleware for authentication in your Next.js app integrated with Keycloak

  1. Install the necessary packages. You'll need the keycloak-js package to handle authentication with Keycloak. You can install it by running the following command:
npm install keycloak-js
Enter fullscreen mode Exit fullscreen mode
  1. Create a new file called keycloak.js in the root of your project.

  2. In keycloak.js, you can configure the Keycloak client using the Keycloak constructor. Here's an example:

import Keycloak from 'keycloak-js';

const keycloak = new Keycloak({
  url: 'YOUR_KEYCLOAK_URL',
  realm: 'YOUR_REALM',
  clientId: 'YOUR_CLIENT_ID',
});

export default keycloak;
Enter fullscreen mode Exit fullscreen mode

Make sure to replace 'YOUR_KEYCLOAK_URL', 'YOUR_REALM', and 'YOUR_CLIENT_ID' with the appropriate values for your Keycloak setup.

  1. In your Next.js _app.js file, you can add the Keycloak authentication logic. Here's an example:
import { useEffect } from 'react';
import keycloak from '../keycloak';

function MyApp({ Component, pageProps }) {
  useEffect(() => {
    keycloak
      .init({ onLoad: 'login-required' })
      .then((authenticated) => {
        if (authenticated) {
          console.log('User is authenticated');
        } else {
          console.log('User is not authenticated');
        }
      })
      .catch((error) => {
        console.error('Keycloak initialization error:', error);
      });
  }, []);

  return <Component {...pageProps} />;
}

export default MyApp;
Enter fullscreen mode Exit fullscreen mode

This code initializes the Keycloak client when the app loads and redirects the user to the Keycloak login page if they are not authenticated.

  1. To protect specific routes with authentication, you can create a custom higher-order component (HOC) that checks if the user is authenticated before rendering the page. Here's an example:
import keycloak from '../keycloak';

export function withAuth(Component) {
  return function AuthenticatedComponent(props) {
    const { authenticated } = keycloak;

    if (!authenticated) {
      return <div>Not authenticated</div>; // Redirect to login page
    }

    return <Component {...props} />;
  };
}
Enter fullscreen mode Exit fullscreen mode

You can then wrap your protected pages with the withAuth

Top comments (1)

Collapse
 
pierrelstan profile image
Stanley

Great tutorial!