Prepare State
In addition to running scripts before building your Nuxt application, for example to validate your environment configuration, you can also define a state that will be available globally to all components and composables.
TIP
Think of the state
as an alternative to the nuxtServerInit
action in Nuxt 2 to make a state available globally (although technically speaking it was a hook and ran on server initialization, not during the build process).
For a simple prepare script, let's retrieve the first todo item from the JSONPlaceholder API and store it, so you can access it from any component, composable, etc.
// `server.prepare.ts`
import { ofetch } from 'ofetch'
import { defineNuxtPrepareHandler } from 'nuxt-prepare/config'
export default defineNuxtPrepareHandler(async () => {
const todoItem = await ofetch('https://jsonplaceholder.typicode.com/todos/1')
return {
state: {
todoItem
}
}
})
INFO
Each state returned by all prepare scripts is merged and stored in .nuxt/module/nuxt-prepare.ts
. It is associated with the alias #nuxt-prepare
. For the example above, the generated file would look like this:
// Generated by nuxt-prepare
export const todoItem = {
userId: 1,
id: 1,
title: 'delectus aut autem',
completed: false
}
export type TodoItem = typeof todoItem
Now that the state is available globally, you can import it from #nuxt-prepare
in any component, page, or layout. If the state is shared between multiple targets, a shared build chunk is created.
import { todoItem } from '#nuxt-prepare'
// Pass initial state to the reactive variable
const todos = ref([todoItem])