pluginsserver-side-renderingnuxt3.js

Nuxt 3 - SSR return 500 with plugin provider


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)


Solution

  • Updated Answer

    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.