---
title: "Bundling Remote Scripts · Nuxt Scripts"
description: "Optimize third-party scripts by bundling them with your app."
canonical_url: "https://scripts.nuxt.com/docs/v0/guides/bundling"
meta:
  "og:description": "Optimize third-party scripts by bundling them with your app."
  "og:image": "https://scripts.nuxt.com/_og/d/c_Docs%2Ctitle_Bundling%2BRemote%2BScripts%2Cdescription_Optimize%2Bthird-party%2Bscripts%2Bby%2Bbundling%2Bthem%2Bwith%2Byour%2Bapp.%2Cheadline_Guides%2Cp_Ii9kb2NzL3YwL2d1aWRlcy9idW5kbGluZyI%2Cs_6-eO3Oz930EoFnDH.png"
  "og:image:height": "600"
  "og:image:type": image/png
  "og:image:width": "1200"
  "og:title": "Bundling Remote Scripts · Nuxt Scripts"
  "twitter:image": "https://scripts.nuxt.com/_og/d/c_Docs%2Ctitle_Bundling%2BRemote%2BScripts%2Cdescription_Optimize%2Bthird-party%2Bscripts%2Bby%2Bbundling%2Bthem%2Bwith%2Byour%2Bapp.%2Cheadline_Guides%2Cp_Ii9kb2NzL3YwL2d1aWRlcy9idW5kbGluZyI%2Cs_6-eO3Oz930EoFnDH.png"
---

> Index of every page on this site: [llms.txt](https://scripts.nuxt.com/llms.txt)

**Guides**

# **Bundling Remote Scripts**

[Copy for LLMs](https://scripts.nuxt.com/docs/v0/guides/bundling.md)

## Background

When you use scripts from other sites on your website, you rely on another server to load these scripts. This can slow down your site and raise concerns about safety and privacy.

### Common problems

- Slower website because it takes time to connect to other servers.
- Safety risks if the other server is hacked.
- Your visitors' data being used inappropriately by other servers.
- Ad blockers or privacy tools might stop these scripts from working.

### How to fix it

By bundling these scripts, you can host them yourself, which helps avoid these issues and keeps your site running smoothly.

## How it Works

During the build process, your code is checked to find any instances of `**useScript**` that need to be bundled.

When a script is identified for bundling, it's downloaded and saved as a public asset at `**/_scripts/[hash].js**`. Here, `**[hash]**` represents the hash of the script's URL.

**Important points about bundling:**

1. You need to have static values for your script URLs and bundling settings.

```ts
// GOOD - Static values allow for bundling
useScript('https://example.com/script.js', {
  bundle: true
})
// BAD - Dynamic values prevent bundling
useScript(scriptSrc, {
  bundle: canBundle
})
```

2. If the original script changes without a URL change, the bundled version won't update in the browser cache. To handle this, use a versioned URL or a cache-busting query parameter.

## Usage

Scripts can be bundled individually or on a global scale using specific settings.

### Script Options

To decide if an individual script should be bundled, use the `**bundle**` option.

```ts
// Opt-in to bundle this specific script
useScript('https://example.com/script.js', {
  bundle: true,
})

// Force download bypassing cache
useScript('https://example.com/script.js', {
  bundle: 'force',
})
```

#### **Bundle Options**

The `**bundle**` option accepts the following values:

- `**false**` - Do not bundle the script (default)
- `**true**` - Bundle the script and use cached version if available
- `**'force'**` - Bundle the script and force download, bypassing cache

**Note**: Using `**'force'**` will re-download scripts on every build, which may increase build time and provide less security.

### Global Bundling

Adjust the default behavior for all scripts using the Nuxt Config. This example sets all scripts to be bundled by default.

nuxt.config.ts

```ts
export default defineNuxtConfig({
  scripts: {
    defaultScriptOptions: {
      bundle: true,
    }
  }
})
```

### Build-time vs Runtime Behavior

Understanding when bundling happens and how it affects runtime behavior is crucial for effective usage.

#### **Build-time Processing**

Bundling occurs during the build phase through static code analysis:

```ts
// ✅ Bundled at build-time (static values)
useScript('https://example.com/script.js', { bundle: true })

// ❌ Cannot be bundled (dynamic values)
const scriptUrl = computed(() => getScriptUrl())
useScript(scriptUrl, { bundle: dynamic.value })
```

#### **Runtime Behavior**

At runtime, bundled scripts behave differently:

```ts
// Original code
useScript('https://example.com/script.js', { bundle: true })

// After build transformation
useScript('/_scripts/abc123.js', {})
```

**Important**: Once bundled, you lose access to the original URL at runtime. If you need the original URL for tracking or analytics, store it separately.

#### **Static URL Requirements**

For bundling to work, the transformer requires **completely static values**:

```ts
// Static string literals
useScript('https://cdn.example.com/lib.js', { bundle: true })

// Static template literals (no variables)
useScript(`https://cdn.example.com/lib.js`, { bundle: true })

// Constants defined at module level
const SCRIPT_URL = 'https://cdn.example.com/lib.js'
useScript(SCRIPT_URL, { bundle: true })
```

#### **Manual Injection Patterns**

When automatic bundling isn't possible, you can manually inject bundled scripts:

Manual Bundling Workaround

```ts
// 1. Bundle during build with static URL
const staticScript = useScript('https://cdn.example.com/static.js', {
  bundle: true,
  trigger: 'manual' // Don't auto-load
})

// 2. Conditionally load based on runtime logic
function loadScript() {
  if (shouldLoadScript.value) {
    staticScript.load()
  }
}

// 3. Alternative: Use multiple static configurations
const scriptVariants = {
  dev: useScript('https://cdn.example.com/dev.js', { bundle: true, trigger: 'manual' }),
  prod: useScript('https://cdn.example.com/prod.js', { bundle: true, trigger: 'manual' })
}

// Load appropriate variant
const currentScript = computed(() =>
  isDev ? scriptVariants.dev : scriptVariants.prod
)
```

#### **Working with Dynamic URLs**

For truly dynamic scenarios, consider these patterns:

Dynamic URL Strategies

```ts
// Option 1: Pre-bundle known variants
const analytics = {
  google: useScript('https://www.googletagmanager.com/gtag/js', { bundle: true }),
  plausible: useScript('https://plausible.io/js/script.js', { bundle: true })
}

// Option 2: Fallback to runtime loading
function loadDynamicScript(url: string) {
  // This won't be bundled, but will work at runtime
  return useScript(url, {
    bundle: false, // Explicitly disable
    trigger: 'manual'
  })
}

// Option 3: Use server-side bundling
// Store script content in your bundle and inject manually
const { $script } = useNuxtApp()
$script.add({
  innerHTML: await $fetch('/api/dynamic-script-content'),
})
```

### Asset Configuration

Use the `**assets**` option in your configuration to customize how scripts are bundled and cached.

nuxt.config.ts

```ts
export default defineNuxtConfig({
  scripts: {
    assets: {
      prefix: '/_custom-script-path/',
      cacheMaxAge: 86400000, // 1 day in milliseconds
    }
  }
})
```

#### **Available Options**

- **`**prefix**`** - Custom path where bundled scripts are served (default: `**/_scripts/**`)
- **`**cacheMaxAge**`** - Cache duration for bundled scripts in milliseconds (default: 7 days)

#### **Cache Behavior**

The bundling system uses two different cache strategies:

- **Build-time cache**: Controlled by `**cacheMaxAge**` (default: 7 days). Scripts older than this are re-downloaded during builds to ensure freshness.
- **Runtime cache**: Bundled scripts are served with 1-year cache headers since they are content-addressed by hash.

This dual approach ensures both build performance and reliable browser caching.

[Edit this page](https://github.com/nuxt/scripts/edit/0.x/docs/content/1.guides/2.bundling.md)

[Markdown For LLMs](https://scripts.nuxt.com/docs/v0/guides/bundling.md)

[**Warmup Strategy** Customize the preload or preconnect strategy used for your scripts.](https://scripts.nuxt.com/docs/v0/guides/warmup) [**Consent Management** Learn how to get user consent before loading scripts.](https://scripts.nuxt.com/docs/v0/guides/consent)

**On this page **

- [Background](#background)
- [How it Works](#how-it-works)
- [Usage](#usage)

```json
{"@context":"https://schema.org","@graph":[{"@id":"https://scripts.nuxt.com/#website","@type":"WebSite","description":"Nuxt Scripts lets you load third-party scripts with better performance, privacy, security and DX. It includes many popular third-parties out of the box.","name":"Nuxt Scripts","url":"https://scripts.nuxt.com/","publisher":{"@id":"https://scripts.nuxt.com/#identity"}},{"@id":"https://scripts.nuxt.com/docs/v0/guides/bundling#webpage","@type":"WebPage","description":"Optimize third-party scripts by bundling them with your app.","name":"Bundling Remote Scripts","url":"https://scripts.nuxt.com/docs/v0/guides/bundling","breadcrumb":{"@id":"https://scripts.nuxt.com/docs/v0/guides/bundling#breadcrumb"},"isPartOf":{"@id":"https://scripts.nuxt.com/#website"},"potentialAction":[{"@type":"ReadAction","target":["https://scripts.nuxt.com/docs/v0/guides/bundling"]}],"primaryImageOfPage":{"@id":"https://scripts.nuxt.com/#logo"}},{"@id":"https://scripts.nuxt.com/#identity","@type":"Organization","name":"Nuxt Scripts","url":"https://scripts.nuxt.com","logo":{"@id":"https://scripts.nuxt.com/#logo"}},{"@id":"https://scripts.nuxt.com/docs/v0/guides/bundling#breadcrumb","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","name":"Nuxt Scripts","item":"https://scripts.nuxt.com/","position":1},{"@type":"ListItem","name":"Documentation","item":"https://scripts.nuxt.com/docs","position":2},{"@type":"ListItem","name":"V0","item":"https://scripts.nuxt.com/docs/v0","position":3},{"@type":"ListItem","name":"Guides","item":"https://scripts.nuxt.com/docs/v0/guides","position":4},{"@type":"ListItem","name":"Bundling Remote Scripts","item":"https://scripts.nuxt.com/docs/v0/guides/bundling","position":5}]},{"@id":"https://scripts.nuxt.com/#logo","@type":"ImageObject","caption":"Nuxt Scripts","contentUrl":"https://scripts.nuxt.com/logo.svg","inLanguage":"en","url":"https://scripts.nuxt.com/logo.svg"}]}
```

## Sitemap

See the full [sitemap](https://scripts.nuxt.com/sitemap.md) for all pages.
