Skip to content

Prepare State

A prepare script's state is generated as typed exports and importable from #nuxt-prepare.

TIP

Similar to Nuxt 2's nuxtServerInit, but runs at build time and generates type-safe imports.

How It Works

This script fetches one todo item and returns it as state:

ts
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 – a later script wins where two set the same key – and generated at .nuxt/module/nuxt-prepare.mjs, accessible via #nuxt-prepare:

ts
// Generated by nuxt-prepare
export const todoItem = {
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

Now that the state is available globally, you can import it from #nuxt-prepare anywhere in your application:

ts
// In any component, composable, page, layout, or plugin
import { todoItem } from '#nuxt-prepare'

const todos = ref([todoItem])
ts
// In Nitro server routes and middleware
import { todoItem } from '#nuxt-prepare'

export default defineEventHandler(() => {
  return { todo: todoItem }
})

TIP

State values are JSON-serialized. See State Serialization for details on supported types.

Released under the MIT License.