HTMLElement undefined error when implementing GovUK FileUpload in Svelte application

I’m working on integrating the enhanced file upload feature from govuk-frontend version 5.9.0 into my Svelte 4 project. When I try to initialize the component, I keep running into an error.

Here’s my current setup:

import {onMount} from 'svelte';
import { FileUpload } from 'govuk-frontend/dist/govuk/components/file-upload/file-upload.mjs';
import { createAll } from 'govuk-frontend/dist/govuk/init.mjs';

onMount(() => {
    createAll(FileUpload);
})

// Template markup follows

The problem is I get this error message:

ReferenceError: HTMLElement is not defined at file:///myapp/node_modules/govuk-frontend/dist/govuk/component.mjs:57:25

I’m looking for a solution to this issue. Ideally I want to avoid using createAll or initAll for all components if there’s a more targeted approach. Has anyone encountered this before?

u nailed it! it’s def a server-side rendering issue. HTMLElement isn’t found on server. maybe check if you’re in a browser first b4 initializing, or use afterUpdate over onMount. gl!

This happens because GovUK Frontend components need a browser environment with HTMLElement, but Svelte’s SSR tries to run the code server-side during hydration. You need to wrap your component initialization in a browser check using Svelte’s browser utility from $app/environment. Import it and update your onMount: if (browser) { createAll(FileUpload); }. If you want more control, skip createAll and target specific elements directly: new FileUpload(document.querySelector('[data-module="govuk-file-upload"]')). This way you decide exactly which components initialize and when.