Description
Describe the feature
As a developer, I often set ssr: false
in nuxt.config.ts
as I prefer to avoid the complexity of handling universal build issues, such as dealing with hydration, increased build times, etc.
However, I miss the easy way to deliver server-side data to clients with server-side plugins, when I can have app/plugins/myplugin.server.ts
and use it to push data to nuxtApp.payload
and then consume it later on the client side. For instance, I may need to push whitelabel data based on the request hostname, or I may need to push user auth data based on cookies without having to use the additional round-trip request on client init.
I kinda managed to achieve what I need with a nitro hook (simplified code below):
import type { NuxtPayload } from "#app"
declare module "#app" {
interface NuxtPayload {
/** Injected by server/plugins/server-data.ts */
serverData: ServerData
}
}
export type ServerData = {
foo: string
}
async function getServerData(): Promise<ServerData> {
return { foo: "foo" }
}
export default defineNitroPlugin((nitro) => {
nitro.hooks.hook("render:html", async (html) => {
const data = await getServerData()
html.bodyAppend.push(`<script>__NUXT__.serverData=${JSON.stringify(data)}</script>`)
})
})
However having to emit raw HTML and fiddling with __NUXT__
in it doesn't seem to be a very satisfying experience, it's needlessly low-level code.
I propose to somehow allow to extend Nuxt payload on the server side with some kind of additional hook that runs with ssr: false
, too.
I suppose this might be implemented as a module, basically moving the above code to a reusable package and somehow allowing it to consume an app-specific server data getter, but my point is that it's still going to be an additional HTML chunk and there rather should be a way to alter the original nuxtData
being serialized by Nuxt itself instead of duplicating this logic in a module.
Additional information
- Would you be willing to help implement this feature?
- Could this feature be implemented as a module?
Final checks
- Read the contribution guide.
- Check existing discussions and issues.