Best Practice for Integrating Matomo 404 Tracking in Shopware 6

We are currently integrating Matomo tracking into our Shopware 6 store and would like to ensure that 404 error pages are properly tracked. We have reviewed the Matomo documentation and understand that the tracking script should be placed within the <head> tag of the 404 page.

However, in Shopware 6, the templating system is based on Twig, and error pages are handled separately from the main layout. We are trying to determine the best approach to include the Matomo tracking script within the <head> tag only when a 404 page is displayed.

So far, we have tried extending the base.html.twig file and adding the tracking script inside {% block head_meta_tags %} while checking for app.request.attributes.get('_route') == 'frontend.error.page'. Would this be the recommended approach, or is there a more optimal way to inject the Matomo script specifically for 404 pages?

Any guidance or best practices you can provide for integrating Matomo tracking in Shopware 6 for 404 pages, would be greatly appreciated.