Site definitions generate 404 with subdomain

To change menu entries, we use this component code:

public function menuItems() {
        if ($this->menuItems !== null) {
            return $this->menuItems;
        }

        if (!strlen($this->property('code'))) {
            return;
        }

        $theme = Theme::getActiveTheme();
        $menu = PagesMenu::loadCached($theme, $this->property('code'));

        if ($menu) {
            $this->menuItems = $menu->generateReferences($this->page);
            $this->menuName = $menu->name;
        }

        $site = \Site::getActiveSite();

        $iterator = function($items) use ($site, &$iterator) {
            foreach ($items as $menuItem) {
                if ($menuItem->type === 'cms-page' && $menuItem->code === 'menu_year') {
                    $menuItem->title .= ' ' . $site->name;
                }
        
                if (!empty($menuItem->items)) {
                    $iterator($menuItem->items);
                }
            }
        };

        $iterator($this->menuItems);

        return $this->menuItems;
    }

When the subdomain (e.g. https://jahresbericht2025.mathilde-escher.ch) is defined it works great. When a subdomain is entered, where the site definition isn’t set, there is a 404, which is good. The only problem is, that the navigation is then using the missing subdomain on all menu items.

How can we fix this?