Search code examples
nuxt.jsnuxt3

How to add inline script tags to Nuxt 3?


I'm trying to integrate Piwik and Intercom into my Nuxt 3 application. Previously, I was able to use the special app.html file in the project root, but that feature is not available anymore. I can use the useHead() utility or the Nuxt configuration, but I don't have a URL for the src attribute, just an inline script.


Solution

  • Turns out, there is a solution that is a bit hidden, because it is not part of the Nuxt documentation as it is the responsibility of the unhead package. The property is called textContent. So using the useHead() utility or the app.head.script array in nuxt.config.ts, it is possible to create an inline script tag:

    useHead({
      script: [
        {
          textContent: `/* Inline code goes here ... */`
          tagPosition: "bodyClose",
        },
      ],
    });
    

    Using the tagPosition property, the script tag can be placed in the head, beginning of body or end of body. Valid values are: 'head' | 'bodyClose' | 'bodyOpen'.

    There is also the innerHTML property. The comments for this say:

    Text content of the tag. Warning: This is not safe for XSS. Do not use this with user input, use textContent instead.

    More information on this in the unhead documentation.