Prepare State
Prepare scripts can return a state object that becomes available globally throughout your application via #nuxt-prepare.
TIP
Similar to Nuxt 2's nuxtServerInit, but runs at build-time and generates type-safe imports.
When to Use State
Use prepare state when you want to:
- Prefetch data – Fetch data at build-time and embed it in your app
- Share constants – Make build-time computed values available everywhere
- Type-safe imports – Get full TypeScript inference without manual type definitions
- Universal access – Use the same data in both client and server code
How It Works
For a simple prepare script, let's retrieve the first todo item from the JSONPlaceholder API and make it available throughout the app:
import { defineNuxtPrepareHandler } from 'nuxt-prepare/config'
import { ofetch } from 'ofetch'
export default defineNuxtPrepareHandler(async () => {
const todoItem = await ofetch('https://jsonplaceholder.typicode.com/todos/1')
return {
state: {
todoItem
}
}
})INFO
State from all prepare scripts is merged and generated at .nuxt/module/nuxt-prepare.mjs, accessible via #nuxt-prepare:
// Generated by nuxt-prepare
export const todoItem = {
userId: 1,
id: 1,
title: 'delectus aut autem',
completed: false
}
export type TodoItem = typeof todoItemNow that the state is available globally, you can import it from #nuxt-prepare anywhere in your application:
// In any component, composable, page, layout, or plugin
import { todoItem } from '#nuxt-prepare'
const todos = ref([todoItem])// In Nitro server routes and middleware
import { todoItem } from '#nuxt-prepare'
export default defineEventHandler(() => {
return { todo: todoItem }
})INFO
State is available in both your Nuxt app (client and server) and Nitro server (API routes, middleware). If state is shared between multiple modules, Nuxt automatically creates a shared build chunk.
TIP
State values are JSON-serialized. See State Serialization for details on supported types.