> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kameleoon.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Implementation with Nuxt

> Integrate Nuxt 4 with Kameleoon Web Experimentation by preloading the engine with anti-flicker protection and executing engine.js after hydration.

# Implementation with Nuxt

Integrate **Nuxt 4** with **Kameleoon Web Experimentation**. This guide covers the steps to preload the Kameleoon engine with **anti-flicker protection** and execute the `engine.js` script **after client hydration**. This setup ensures optimal performance, visual stability, and compatibility with the Nuxt rendering lifecycle.

Access reference implementations for:

* [Nuxt 3](https://github.com/Kameleoon/setup-engine-nuxt-3)
* [Nuxt 2](https://github.com/Kameleoon/setup-engine-nuxt-2)

### Access the production-ready Nuxt 4 integration

Find the production-ready repository here:
[https://github.com/Kameleoon/setup-engine-nuxt-4](https://github.com/Kameleoon/setup-engine-nuxt-4)

Before starting, **replace the sitecode value** in [`integrations/Kameleoon/sitecode.ts`](https://github.com/Kameleoon/setup-engine-nuxt-4/blob/main/integrations/Kameleoon/sitecode.ts).

<Note>
  Depending on when you created your Kameleoon project, your scripts may reside on `kameleoon.eu` or `kameleoon.io`. Always use the domain from your project settings in the Kameleoon App.
</Note>

***

## Overview

### Workflow

| Phase                  | Description                                           | Component                          |
| ---------------------- | ----------------------------------------------------- | ---------------------------------- |
| **SSR Rendering**      | Inject the preload link and anti-flicker CSS          | `KameleoonHead.vue`                |
| **Client Hydration**   | Vue hydrates the DOM                                  | —                                  |
| **Post Hydration**     | Load the Kameleoon engine asynchronously              | `KameleoonScriptLoader.client.vue` |
| **Fallback Safe-Exit** | Remove anti-flicker CSS if the script fails or stalls | `KameleoonScriptLoader.client.vue` |

### Quick setup

1. Add the `integrations/Kameleoon` folder to your Nuxt project.
2. Import and register both integration components in your layout (we recommend `layouts/default.vue`). See: [Usage in `default.vue`](#usage-in-defaultvue).

***

## Components

The integration uses **two Vue components** executed at different stages of the Nuxt rendering pipeline:

| Component                          | Execution Context                | Purpose                                                             |
| ---------------------------------- | -------------------------------- | ------------------------------------------------------------------- |
| `KameleoonHead.vue`                | **Server-side (SSR)**            | Injects the preload directive and anti-flicker CSS before hydration |
| `KameleoonScriptLoader.client.vue` | **Client-side (post hydration)** | Loads the engine script and manages the anti-flicker timeout        |

This approach provides fast rendering, stable UI behavior, and full compatibility with Nuxt hydration.

***

### 1. `KameleoonHead.vue`

`KameleoonHead.vue` runs **only during server-side rendering**. It prepares the page for a flicker-free experience by:

* Injecting anti-flicker CSS during SSR.
* Preloading the Kameleoon engine (`engine.js`) so the browser fetches it early.

```ts theme={null}
<script setup>
import { SITECODE_SRC } from "../sitecode";
</script>

<template>
    <Head>
        <!-- preload script early -->
        <Link rel="preload" :href="SITECODE_SRC" as="script" fetchpriority="high" />

        <!-- anti-flicker CSS -->
        <Style id="kameleoonLoadingStyleSheet">
            html::after { content: ''; position: fixed; inset: 0; background: #fff; z-index: 2147483647; }
        </Style>
    </Head>
</template>
```

See [`KameleoonHead.vue`](https://github.com/Kameleoon/setup-engine-nuxt-4/blob/main/integrations/Kameleoon/components/KameleoonHead.vue) on GitHub.

***

### 2. `KameleoonScriptLoader.client.vue`

`KameleoonScriptLoader.client.vue` executes **on the client after hydration**.

The component:

* Removes the anti-flicker stylesheet when the page is ready.
* Loads the `engine.js` script dynamically.
* Handles timing and fallback behavior for slow script loading.

```ts theme={null}
<script setup>
defineOptions({ name: "KameleoonScriptLoader" });

import { nextTick, onMounted } from "vue";
import { SITECODE_SRC } from "~/integrations/Kameleoon/sitecode";

onMounted(async () => {
    await nextTick();

    const kameleoonLoadingTimeout = 500;

    window.kameleoonQueue = window.kameleoonQueue || [];
    window.kameleoonStartLoadTime = Date.now();

    window.kameleoonDisplayPage = function (fromEngine) {
        if (!fromEngine) {
            window.kameleoonTimeout = true;
        }
        document.getElementById("kameleoonLoadingStyleSheet")?.remove();
    };

    window.kameleoonDisplayPageTimeOut = setTimeout(window.kameleoonDisplayPage, kameleoonLoadingTimeout);

    const alreadyLoaded = document.querySelector(`script[src*="${SITECODE_SRC}"]`);
    if (!alreadyLoaded) {
        const script = document.createElement("script");
        script.src = SITECODE_SRC;
        script.async = true;
        document.head.appendChild(script);
    }
});
</script>

<template>
    <!-- nothing rendered -->
</template>
```

See [`KameleoonScriptLoader.client.vue`](https://github.com/Kameleoon/setup-engine-nuxt-4/blob/main/integrations/Kameleoon/components/KameleoonScriptLoader.client.vue) on GitHub.

<Note>
  The default anti-flicker timeout is `750 ms`. Adjust `kameleoonLoadingTimeout` as needed.
</Note>

***

## Usage in `default.vue`

Use the following example to combine components in your layout:

```ts theme={null}
<script setup>
import KameleoonHead from "~/integrations/Kameleoon/components/KameleoonHead.vue";
import KameleoonScriptLoader from "~/integrations/Kameleoon/components/KameleoonScriptLoader.client.vue";
</script>

<template>
    <!-- SSR: preload + anti-flicker -->
    <KameleoonHead />

    <!-- Client: load script after hydration -->
    <KameleoonScriptLoader />

    <!-- Layout UI -->
    <div class="min-h-screen bg-background font-inter">
        <Navigation />

        <main class="container mx-auto px-4 py-8">
            <NuxtPage />
        </main>
    </div>
</template>
```

See [`default.vue`](https://github.com/Kameleoon/setup-engine-nuxt-4/blob/main/layouts/default.vue) on GitHub.

***

## Key takeaways

* Prevent hydration mismatch warnings.
* Ensure a flicker-free experience before Kameleoon initialization.
* Load the script **only once**, including during SPA navigation.
* Maintain compatibility with layouts, pages, dynamic routes, and conditional rendering.

With this configuration, your Nuxt application loads and executes Kameleoon reliably without affecting rendering stability.
