I'm new with Nuxt, and I try to understand plugins in SSR and CSR.
I follow the helloWorld test in the documentation.
With CSR It works perfectly (/plugins/hello.ts or /plugins/hello.client.ts)
But with SSR (/plugins/hello.server.ts) I've got :
[GET] 500 $setup.$hello is not a function
Someone can explain me why it doesn't work with server side rendering ?
plugins/hello.(client or server or '').ts
export default defineNuxtPlugin(() => {
return {
provide: {
hello: (msg: string) => `Hello ${msg}!`
}
}
})
pages/hello.vue
<script setup lang="ts">
const { $hello } = useNuxtApp()
</script>
<template>
<div>
{{ $hello('world') }}
</div>
</template>
Documentation (https://nuxt.com/docs/guide/directory-structure/plugins)
Updated Answer
hello.server.ts
means that the hello plugin is only available on the server and as such will be undefined on the client
hello.client.ts
means that the hello plugin is only available on the client and as such will be undefined on the server
hello.ts
means that the hello plugin is available both on the server and on the client. This is what you want in most cases - it does not mean your aren't using SSR.
So the error you see when using hello.server.ts
means that you're trying to access the plugin on the client where it is supposed to be inaccesible.
If you truly wanted to create a server side only plugin you would have to make sure it is never called on the client.
For example:
HelloWorld.vue
<script setup lang="ts">
const providedValue = ref();
if (import.meta.server) {
const { $hello } = useNuxtApp();
providedValue.value = $hello('World!');
console.log(providedValue.value);
}
</script>
<template>
<div>
{{ providedValue }}
</div>
</template>
hello.server.ts
export default defineNuxtPlugin(() => {
return {
provide: {
hello: (msg: string) => `Hello ${msg}!`,
},
};
});
Original Answer
if I remove the setup in my in my .vue file I've got this error
What exactly do you mean by setup
here?
The following does appear to be working correctly using the newest Nuxt version. I've just tried it on Stakblitz.