Core Concepts
Build-Time vs Runtime
Prepare scripts run during the build process, not at runtime:
nuxt dev/build → Prepare scripts run → Nuxt builds your app → App runsThis means:
- Scripts run once per build, not on every request
- Expensive operations (API calls, data fetching) don't impact runtime performance
- Results are embedded into your application at build-time
The Problem Nuxt Prepare Solves
Nuxt's configuration file (nuxt.config.ts) doesn't support async operations. This means you can't:
// ❌ This doesn't work in nuxt.config.ts
export default defineNuxtConfig({
runtimeConfig: {
apiUrl: await fetchApiUrl() // Error: top-level await
}
})Nuxt Prepare fills this gap by running async code before the configuration is finalized.
How It Works
1. Script Execution
When Nuxt builds your app, prepare scripts are executed in order (or in parallel if configured). Each script returns a result that can modify your Nuxt configuration or pass data to your app.
2. Generated Files
The module generates files in .nuxt/module/:
nuxt-prepare.mjs – Exported state values:
// Generated by nuxt-prepare
export const todos = [
{ id: 1, title: 'Learn Nuxt Prepare' }
]nuxt-prepare.d.ts – Type definitions:
// Generated by nuxt-prepare
export declare const todos: [{ id: number, title: string }]
export type Todos = typeof todos3. Module Alias
The generated files are available via the #nuxt-prepare alias, which works in:
- Nuxt app – Components, composables, pages, layouts
- Nitro server – API routes, middleware, server utilities
// Works everywhere
import { todos } from '#nuxt-prepare'State Serialization
State values are JSON-serialized during code generation. This means:
- ✅ Objects, arrays, strings, numbers, booleans, null
- ❌ Functions, classes, symbols, undefined
// ✅ This works
state: {
config: { api: 'https://api.example.com' },
items: [1, 2, 3]
}
// ❌ This doesn't work
state: {
handler: () => console.log('hello'), // Functions are lost
data: undefined // Becomes null
}Return Options
Prepare scripts can return:
state– Pass build-time data as importable constants via#nuxt-prepareruntimeConfig– Set runtime configuration accessible viauseRuntimeConfig()appConfig– Set app configuration accessible viauseAppConfig()
See Runtime & App Config for detailed guidance on when to use each option.