Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a script block to head in Nuxt 3?

I simply want to add a script block in the head tag.

Example

<script>
    alert('hello, world!');
</script>

I spent hours to figure out a solution for something as simple as this. There are tons of answers about adding inline scripts, but none for the script block for Nuxt 3

How can we do this in Nuxt 3?

like image 770
Moon Avatar asked Nov 17 '25 02:11

Moon


1 Answers

Okay, I found the answer. There are 3 possible solutions.

Solution 1

<template>
  <Script children="console.log('Hello, world!');" />
</template>

Solution 2

<script setup>
useHead({
  script: [{ children: "console.log('Hello, world!');" }],
});
</script>

Solution 3

import { defineNuxtConfig } from 'nuxt';

export default defineNuxtConfig({
  app: {
    head: {
      script: [{ children: "console.log('Hello, world!');" }],
    },
  },
});
like image 134
Moon Avatar answered Nov 18 '25 17:11

Moon