onPrehydrate is a composable lifecycle hook that allows you to run a callback on the client immediately before Nuxt hydrates the page.
nuxt-time and @nuxtjs/color-mode manipulate the DOM to avoid hydration mismatches.Call onPrehydrate in the setup function of a Vue component (e.g., in <script setup>) or in a plugin. It only has an effect when called on the server and will not be included in your client build.
export function onPrehydrate (callback: (el: HTMLElement) => void): void
export function onPrehydrate (callback: string | ((el: HTMLElement) => void), key?: string): undefined | string
| Parameter | Type | Required | Description |
|---|---|---|---|
callback | ((el: HTMLElement) => void) | string | Yes | A function (or stringified function) to run before Nuxt hydrates. It will be stringified and inlined in the HTML. Should not have external dependencies or reference variables outside the callback. Runs before Nuxt runtime initializes, so it should not rely on Nuxt or Vue context. |
key | string | No | (Advanced) A unique key to identify the prehydrate script, useful for advanced scenarios like multiple root nodes. |
undefined when called with only a callback function.data-prehydrate-id attribute for advanced use cases.// Run code before Nuxt hydrates
onPrehydrate(() => {
console.log(window)
})
// Access the root element
onPrehydrate((el) => {
console.log(el.outerHTML)
// <div data-v-inspector="app.vue:15:3" data-prehydrate-id=":b3qlvSiBeH:"> Hi there </div>
})
// Advanced: access/set `data-prehydrate-id` yourself
const prehydrateId = onPrehydrate((el) => {})
</script>
<template>
<div>
Hi there
</div>
</template>