Skip to content

Instantly share code, notes, and snippets.

@suhodolskiy
Last active February 7, 2025 23:38
Show Gist options
  • Select an option

  • Save suhodolskiy/1af5795fc33ba079dfaaf348e1f9f1ca to your computer and use it in GitHub Desktop.

Select an option

Save suhodolskiy/1af5795fc33ba079dfaaf348e1f9f1ca to your computer and use it in GitHub Desktop.
Villus Nuxt Plugin (SSR)
import { defaultPlugins, useClient } from 'villus'
import { authPlugin } from './auth'
import { ssrPlugin } from './ssr'
export default defineNuxtPlugin((nuxtApp) => {
const config = useRuntimeConfig()
nuxtApp.hook('vue:setup', () => {
useClient({
url: import.meta.server ? config.apiUrl : config.public.apiUrl,
use: [authPlugin(), ssrPlugin(), ...defaultPlugins()],
})
})
})
import type {
ClientPlugin,
ClientPluginContext,
ClientPluginOperation,
OperationResult,
} from 'villus'
interface StateSSR {
[k: string]: OperationResult | undefined
}
export const ssrPlugin = (): ClientPlugin => {
const state = useState<StateSSR>('__VILLUS__', () => ({}))
const getState = (ctx: ClientPluginOperation): OperationResult | undefined =>
state.value[ctx.key]
const setState = (ctx: ClientPluginOperation, result: OperationResult) =>
(state.value[ctx.key] = result)
const clearState = (ctx: ClientPluginOperation) =>
(state.value[ctx.key] = undefined)
return ({ afterQuery, useResult, operation }: ClientPluginContext) => {
if (operation.type !== 'query') {
return
}
if (import.meta.server) {
afterQuery((result) => {
setState(operation, result)
})
}
if (import.meta.client) {
const ssrState = getState(operation)
if (ssrState) {
clearState(operation)
return useResult(ssrState, true)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment