3 ways to add javascript in the head tag of your Nuxt 3 app
I'll show you how to add javascript in your head tag of your Nuxt app.
Introduction
👋 Hi all, have you come into a situation where you need a script to run before the document load inside the <head>
tag of your app? I came across this situation when my app is running dark mode theme but flashing light mode theme for a second on reload.
You can check out the article here and learn how to add dark mode to your Nuxt app in just 15 mins. Now let me show you 3 ways you can add script inside the <head>
tag of your Nuxt app.
Using nuxt.config.ts
Using nuxt.config.ts will make your script runs on every page of your app. If you want to have the control of which page to run the script, check out useHead
instead.
//nuxt.config.tsexport default defineNuxtConfig({ app: { head: { script: [{ children: "console.log('Hello, world!');" }], // Runs on every page of your app }, },});
Using useHead
useHead is the most comman way to add script in your head
tag.
There is also useHeadSafe for untrusted script. Just drop the code on the vue page you want it to run in or inside the app.vue
page to run it on every pages.
<script lang="ts" setup>useHead({ script: [{ children: "console.log('Hello, world!');" }],});</script>
Using Nitro Plugin
Nitro Plugin offers a powerful way to extend the html and mutate it before it's sent to the client. Create a Typescript file, in my case my-plugin.ts
inside the server/plugins
folder.
//server/plugins/my-plugin.tsexport default defineNitroPlugin((nitroApp) => { nitroApp.hooks.hook('render:html', (html, { event }) => { html.head.push(`<script>console.log('Hello, world!')</script>`) })})
✨ That's the 3 ways to add script in your Nuxt app <head>
tag, check out this article where we put this into practice with implementing our dark mode feature in 15 mins!