Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@nuxt/scripts

Package Overview
Dependencies
Maintainers
7
Versions
58
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@nuxt/scripts

Next-gen Scripts for Nuxt

  • 0.1.5
  • Source
  • npm
  • Socket score

Version published
Maintainers
7
Created
Source

npm version npm downloads License Nuxt Volta

Nuxt Scripts

Better Privacy, Performance, and DX for Third-Party Scripts in Nuxt Apps.

Features

  • 🪨 useScript
    • 🦥 Improve your site performance with better script loading strategies
    • 🎃 Powerful proxy API for SSR handling, lazy loading, and error handling
  • (TODO) Registry for third-party scripts in Nuxt
  • ⏬ Serve scripts from your own server
  • 🕵️ Privacy Features - Trigger scripts loading on consent.
  • 🪵 DevTools integration - View your script with their status and see function logs

Background

Loading third-party IIFE scripts using useHead composable is easy. However, things start getting more complicated quickly around SSR, lazy loading, and type safety.

Nuxt Scripts was created to solve these issues and more with the goal of making third-party scripts more performant, have better privacy and be better DX overall.

Quick Start

To get started, simply run:

npx nuxi@latest module add @nuxt/scripts

To start using Nuxt Scripts, you can use the useScript composable to load your third-party scripts.

Confetti Example

If you want to get a feel for how the module works, you can load the js-confetti library:

interface JSConfettiApi { addConfetti: (options?: { emojis: string[] }) => void }
const { addConfetti } = useScript<JSConfettiApi>('https://cdn.jsdelivr.net/npm/js-confetti@latest/dist/js-confetti.browser.js', {
  trigger: 'onNuxtReady', // load on onNuxtReady
  assetStrategy: 'bundle', // script will be served from your server instead of cdn.jsdelivr.net
  use() {
    return new window.JSConfetti()
  },
})
// useScript is non-blocking, this will run once the script loads
addConfetti({ emojis: ['🌈', '⚡️', '💥', '✨', '💫', '🌸'] })

Guides

Using The Registry (TODO)

The registry is a collection of composables and Nuxt Modules that directly integrate with Nuxt Scripts.

To use a script from the registry, simply use the composable. Consult the below table for the available scripts.

KeyDescriptionComposableSource
cloudflare-web-analyticsCloudflare Web AnalyticsuseScriptCloudflareWebAnalyticsCore
confettiJS ConfettiuseScriptCloudflareAnalyticsCore
facebook-pixelFacebook PixeluseScriptFacebookPixelCore
fathom-analyticsFathom AnalyticsuseScriptFathomAnalyticsCore
hotjarHotjaruseScriptHotjarCore
intercomIntercomuseScriptIntercomCore
segmentSegmentuseScriptSegmentCore
google-analyticsGoogle AnalyticsuseScriptGoogleAnalyticsNuxt Third Party Capital
google-tag-managerGoogle Tag ManageruseScriptGoogleTagManagerNuxt Third Party Capital
google-mapsGoogle MapsuseScriptGoogleMapsNuxt Third Party Capital
cloudflare-turnstileCloudFlare TurnstileuseCloudflareTurnstileNuxt Cloudflare Turnstile

More coming soon!

Loading Scripts Globally

If you prefer a config based approach, you can load scripts globally by defining them in your nuxt.config.ts.

export default defineNuxtConfig({
  scripts: {
    globals: [
      'https://cdn.jsdelivr.net/npm/js-confetti@latest/dist/js-confetti.browser.js',
      {
        assetStrategy: 'bundle'
      }
    ]
  }
})

Bundling Scripts

Bundling scripts can allow you to serve them from your own server, improving privacy and performance. It can also help to get around ad blockers and other privacy tools when you need a script to load.

You can opt-in to have your scripts bundled by using the assetStrategy option. As this is analyzed at build time, you must define it statically.

useScript('https://cdn.jsdelivr.net/npm/js-confetti@latest/dist/js-confetti.browser.js', {
  assetStrategy: 'bundle'
})
// js-confetti.browser.js will be downloaded and bundled with your app as a static asset

Overriding Scripts

When working with modules that use Nuxt Script, you may want to modify the behavior of the script. This is especially useful for changing the asset strategy of a script as it needs to be defined statically.

To do so you can use the overrides module option.

export default defineNuxtConfig({
  scripts: {
    overrides: {
      // the key is either a specified key or the script src
      confetti: {
        assetStrategy: 'bundle'
      }
    }
  }
})

Nuxt Scripts provides a createScriptConsentTrigger composable that allows you to load scripts based on user's consent.

You can either use it by providing a resolvable consent (ref, promise) option or by using accept().

export const agreedToCookiesScriptConsent = createScriptConsentTrigger()
// ...
useScript('https://www.google-analytics.com/analytics.js', {
  trigger: agreedToCookiesScriptConsent
})
// ...
agreedToCookiesScriptConsent.accept()
const agreedToCookies = ref(false)
useScript('https://www.google-analytics.com/analytics.js', {
  // will be loaded in when the ref is true
  trigger: createScriptConsentTrigger({
    consent: agreedToCookies
  })
})

Sending Page Events

When using tracking scripts, it's common to send an event when the page changes. Due to Nuxt's head implementation being async, the page title is not always available on route change immediately.

useAnalyticsPageEvent solves this by providing you with the page title and path when they change.

useAnalyticsPageEvent(({ title, path }) => {
  // triggered on route change
  gtag('event', 'page_view', {
    page_title: title,
    page_location: 'https://example.com',
    page_path: path
  })
})

API

useScript

Please see the useScript documentation.

createScriptConsentTrigger

(options: ScriptConsentTriggerOptions) => { accept: () => void } & Promise

Creates a consent trigger for a script.

Arguments
  • consent (optional) - A ref, promise, or boolean that resolves to the user's consent. Defaults to undefined.
  • loadOnNuxtReady (optional) - If consent is provided before the browser idle, wait for the browser to be idle before loading the script. Defaults to false.
Returns
  • accept - A function that can be called to accept the consent and load the script.
const trigger = createScriptConsentTrigger()
// accept the consent and load the script
trigger.accept()

useAnalyticsPageEvent

(callback?: (page: { title: string, path: string }) => void) => Ref<{ title: string, path: string }>

Access the current page title and path and trigger an event when they change.

Arguments
  • callback (optional) - A function that will be called when the page title or path changes.
Returns
  • A ref containing the current page title and path.
const pageCtx = useAnalyticsPageEvent()
// will always be the current page title
pageCtx.value.title

License

Licensed under the MIT license.

📑 License

Published under the MIT License

FAQs

Package last updated on 30 Mar 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc