Keycloakify
HomeGitHubStorybookAlternative to keycloak-js
v11
  • Documentation
  • Release Notes & Upgrade Instructions
  • FAQ
v11
  • Quick Start
  • CSS Customization
  • Testing your Theme
    • Outside of Keycloak
    • Inside of Keycloak
  • Deploying Your Theme
  • Integrating Keycloakify in your Codebase
    • Vite
    • Create-React-App / Webpack
    • yarn/npm/pnpm/bun Workspaces
    • Turborepo
    • Nx
    • Angular Workspace
  • Common Use Case Examples
    • Using a Component Library
    • Custom Fonts
    • Changing the background image
    • Adding your Logo
    • Using Tailwind
    • Dark Mode Persistence
  • Features
    • Internationalization and Translations
      • Basic principles
      • Previewing Your Pages in Different Languages
      • Adding New Translation Messages or Changing the Default Ones
      • Adding Support for Extra Languages
    • Theme Variants
    • Environment Variables
    • Styling a Custom Page Not Included in Base Keycloak
    • Integrating an Existing Theme into Your Keycloakify Project
    • Compiler Options
      • --project
      • keycloakVersionTargets
      • environmentVariables
      • themeName
      • startKeycloakOptions
      • themeVersion
      • accountThemeImplementation
      • postBuild
      • XDG_CACHE_HOME
      • kcContextExclusionsFtl
      • keycloakifyBuildDirPath
      • groupId
      • artifactId
      • Webpack specific options
        • projectBuildDirPath
        • staticDirPathInProjectBuildDirPath
        • publicDirPath
  • Page-Specific Guides
    • Registration Page
    • Terms and Conditions Page
  • Theme types
    • Differences Between Login Themes and Other Types of Themes
    • Account Theme
      • Single-Page
      • Multi-Page
    • Email Theme
    • Admin Theme
Powered by GitBook
On this page

Was this helpful?

Edit on GitHub
  1. Integrating Keycloakify in your Codebase

Vite

Last updated 2 months ago

Was this helpful?

🚨 WARNING: ADVANCED USERS ONLY 🚨

If you're unsure what this section is about, this approach is NOT for you. Instead, follow

This section is only for developers who already have an existing project and need to integrate a Keycloak theme within it to reuse existing components and styles.

🔹 If you're just trying to get started with Keycloakify, stop here— provide a much simpler and recommended path.

🔹 If you proceed without fully understanding how this approach differs from the starter project, you will likely get confused about what you’re actually doing, attempt to simplify things, and end up hitting a roadblock.

If you have a Vite project you can integrate Keycloakify directly inside it.

Svelte: Although this guide uses React as an example it's also applicable for Svelte, you just need to adapt it when relevent.

Let's assume we're working with a freshly initialized Vite project.

Before anything, make sure to commit all your pending changes so you can easily revert changes if need be.

Let's start by installing Keycloakify (and optionally Storybook) to our project:

yarn add keycloakify
# Installing storybook is optional
yarn add --dev storybook @storybook/react @storybook/react-vite
pnpm add keycloakify
# Installing storybook is optional
pnpm add --dev storybook @storybook/react @storybook/react-vite
bun add keycloakify
# Installing storybook is optional
bun add --dev storybook @storybook/react @storybook/react-vite
npm install keycloakify
# Installing storybook is optional
npm install --save-dev storybook @storybook/react @storybook/react-vite
cd my-react-app
git clone https://github.com/keycloakify/keycloakify-starter tmp
mv tmp/src src/keycloak-theme

# Note for the following command: If you already have Storybook setup
# in your project you can skip this.
# Only make sure you have `staticDirs: ["../public"]` in your .storybook/main.ts
mv tmp/.storybook .

rm -rf tmp
rm src/keycloak-theme/vite-env.d.ts
mv src/keycloak-theme/main.tsx src/main.tsx

Now you want to modify your entry point so that:

  • If the kcContext global is defined, render your Keycloakify theme

  • Else, reder your App as usual.

Let's say, for example, your src/main.tsx file currently looks like this:

src/main.tsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import "./index.css";
import { MyProvider } from "./MyProvider";

createRoot(document.getElementById('root')!).render(
    <StrictMode>
      <MyProvider>
        <App />
      </MyProvider>
    </StrictMode>,
);

You want to rename this file to src/main.app.tsx (for example) and modify it as follows:

src/main.app.tsx
import App from "./App.tsx";
import "./index.css";
import { MyProvider } from "./MyProvider.tsx";

export default function AppEntrypoint() {
  return (
    <MyProvider>
      <App />
    </MyProvider>
  )
}

Then you want to create the following src/main.tsx file, you can copy and paste the following code (it does not need to be adapted):

src/main.tsx
import { createRoot } from "react-dom/client";
import { StrictMode, lazy, Suspense } from "react";
import { KcPage, type KcContext } from "./keycloak-theme/kc.gen";
const AppEntrypoint = lazy(() => import("./main.app"));

// The following block can be uncommented to test a specific page with `yarn dev`
// Don't forget to comment back or your bundle size will increase
/*
import { getKcContextMock } from "./keycloak-theme/login/KcPageStory";

if (import.meta.env.DEV) {
    window.kcContext = getKcContextMock({
        pageId: "register.ftl",
        overrides: {}
    });
}
*/

createRoot(document.getElementById("root")!).render(
    <StrictMode>
        {window.kcContext ? (
            <KcPage kcContext={window.kcContext} />
        ) : (
            <Suspense>
                <AppEntrypoint />
            </Suspense>
        )}
    </StrictMode>
);

declare global {
    interface Window {
        kcContext?: KcContext;
    }
}

Question:

Why do my main application and Keycloak theme share the same entry point?

Answer:

To simplify the build process. If you don't want it to negatively impact the performance of your application, it's essential to understand the following points:

  • Different Contexts: The application (App) and Keycloak page (KcPage) are mounted in very different contexts. Avoid sharing providers between the two at the main.tsx file level. The true entry point of your application is the AppEntrypoint component defined in main.app.tsx, while the entry point for your Keycloak theme is the KcPage component. Be careful about what code is shared between them.

  • Responsibility of main.tsx: The main.tsx file should only determine the context (either the application or Keycloak) and mount the appropriate component (App or KcPage). It should not contain any substantial logic or dependencies.

  • Performance Considerations: Keep main.tsx as lightweight as possible to avoid increasing the initial load time of both your main application and login pages. For example, do not load any state management libraries like redux-toolkit at this level.

vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { keycloakify } from "keycloakify/vite-plugin";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(), 
    keycloakify({
        accountThemeImplementation: "none"
    })
  ],
})

Finally you want to add to your package.json a script for building the theme and another one to start storybook.

package.json
{
  "name": "my-react-app",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc -b && vite build",
    "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview",
    "build-keycloak-theme": "npm run build && keycloakify build",
    "storybook": "storybook dev -p 6006"
  },
  // ...

Last setp is to exclude from your html <head /> things that aren't relevent in the context of Keycloak pages.

Do not blindly copy/paste, this is just an example!

You have to figure out what does and does not make sense to be in the <head/> of your Keycloak UI pages.

public/index.html
<!doctype html>
<html>

<head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <meta name="keycloakify-ignore-start">
    <title>ACME Dashboard</title>
    <script>
        window.ENV = {
            API_ADDRESS: '${API_ADDRESS}',
            SENTRY_DSN: '${SENTRY_DSN}'
        };
    </script>
    <meta name="keycloakify-ignore-end">
    
    <!-- ... -->

</head>

<!-- ... -->

In the above example we tell Keycloakify not to include the <title> because Keycloakify will set it dynamically to something like "ACME- Login" or "ACME - Register".

We also exclude a placeholder script for injecting environnement variables at container startup.

You can run npm run build-keycloak-theme, the JAR distribution of your Keycloak theme will be generated in dist\_keycloak.

You're now able to use all the Keycloakify commands (npx keycloakify --help) from the root of your project.

Next we want to move the relevant files from into our project:

If you have some top level await and you don't know how to deal with thoses, join , I can help you out.

You also need to use Keycloakify's Vite plugin. Here we don't provide any but you probably at least want to define .

Leave accountThemeImplementation set to "none" for now. To initialize the account theme refer to .

That's it, your project is ready to go!

If you're currently using or to manage user authentication in your app you might want to checkout , the alternative from the Keycloakify team.

If you have any issues ! We're here to help!

🎉
the starter template
the discord server
build options
keycloakVersionTargets
this guide
keycloak-js
react-oidc-context
oidc-spa
reach out on Discord
Testing your Theme
https://github.com/keycloakify/docs.keycloakify.dev/blob/v11/integration-keycloakify-in-your-codebase/broken-reference/README.md
the Quick Start Guide and fork the starter project.
the starter projects
Creating a new vite project with yarn create vite. Don't do that, use your existing project.
Our codebase before installing Keycloakify
State of your codebase after bringing in the Keycloakify boilerplate code. Note thate the keycloak-theme (or keycloak_theme) directory can be located anywhere under your src directory.