klaro-js icon indicating copy to clipboard operation
klaro-js copied to clipboard

Klaro not working as expected after page navigation in Nextjs app router

Open davidbucka opened this issue 6 months ago • 1 comments

Klaro Config

{
    "acceptAll": true,
    "cookieName": "klaro-consent",
    "default": false,
    "elementID": "klaro",
    "hideDeclineAll": false,
    "htmlTexts": true,
    "lang": "de",
    "mustConsent": false,
    "noNotice": false,
    "poweredBy": "https://klaro.org/",
    "services": [
        {
            "cookies": [],
            "name": "soundcloud",
            "onlyOnce": true,
            "optOut": true,
            "purposes": [
                "external-content"
            ],
            "required": false
        },
    ],
    "storageMethod": "cookie",
    "testing": false,
    "translations": [...]
    "version": 2
}

Example of init function

export async function initKlaro(
  services: Project["cookieConsent"]["services"]
) {
  if (typeof window !== "undefined") {
    const Klaro = await import("klaro")
    const config = await createKlaroConfig(services)
    window.klaroConfig = config
    window.klaro = Klaro
    Klaro.setup(config)
  }
}

export function CookieConsentSetup({ project }: { project: ProjectResponse }) {
  const pathname = usePathname()

  const setupKlaro = React.useCallback(
    () => initKlaro(project.cookieConsent.services),
    [project.cookieConsent.services]
  )

  React.useEffect(() => setupKlaro(), [setupKlaro, pathname])

  return <div id="klaro" />
}

Example of iframe

export function IframeExample() {
  return (
    <div>
      <iframe
        allow="autoplay"
        data-name="soundcloud"
        data-src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/2095559661..."
        height="300"
        width="100%"
      ></iframe>
    </div>
  )
}

Current behavior

When navigating between pages using Next.js client-side navigation (e.g., via <Link> or useRouter), and giving consent on a page where no iframe is on, the iframes src attribute is not set after navigating to a page with an iframe.

I already tried calling Klaro.setup(config) after each page change and experimented with setTimeout() and so on, but it seems it does not re-process iframes after page change.

davidbucka avatar Jul 01 '25 11:07 davidbucka

Hi, did you fix this yourself?

alexander-dal avatar Oct 01 '25 17:10 alexander-dal