Skip to content

Prepare Data ​

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

Return Data From a Script ​

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

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 {
    data: {
      todoItem
    }
  }
})

Import It From #nuxt-prepare ​

Data from all prepare scripts is merged – a later script wins where two set the same key. Each key becomes a named export, typed read-only with its literal values rather than widened ones – todoItem.id is 1, not number – plus a type alias named after it:

ts
// Generated by nuxt-prepare
type _DeepReadonly<T> = T extends object ? { readonly [K in keyof T]: _DeepReadonly<T[K]> } : T

export declare const todoItem: _DeepReadonly<{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}>
export type TodoItem = typeof todoItem
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 }
})

The types are read-only because the server shares one instance of each import across all requests, so a change would reach every later request.

A key that cannot be an export name, such as build-region or the reserved word default, stops the build, and so do two keys whose type aliases match, such as buildRegion and build_region, or a key like _ that gives no type alias name.

What Survives Serialization ​

Data values are JSON-serialized:

  • Objects, arrays, strings, numbers, and booleans survive, and so does null inside an array or object.
  • Functions, symbols, and undefined are dropped from an object and become null in an array.
  • A data key set to a function or symbol is exported as undefined; one set to undefined or null gets no export at all.
  • A Date arrives as its ISO string, a Map or Set as {}.

Released under the MIT License.