Silve2611
Silve2611

Reputation: 2278

Plugin only server side

I have a plugin that I don't want the client to see. Unfortunately it is allways built both for the server and the client. How can this be prevented?

<template>
    <div>
        Test
    </div>
</template>

<script>
    import getAll from '~/plugins/api'
    export default {
        asyncData (context, callback) {
            getAll(function(data){
                callback(null,data);
            })
        }
    }
</script>

This is my .vue file. The fetch of the data is working but i can also See the code from the client side which i don't want.

Upvotes: 6

Views: 3442

Answers (2)

Suki
Suki

Reputation: 367

Adding a .server suffix to the file should work for nuxt3, for example if your file is myPlugin.ts rename it to myPlugin.server.ts - this will only be called on the server.

Upvotes: 2

Nicolas Pennec
Nicolas Pennec

Reputation: 7631

Maybe you can use the context.isServer property.
It's a boolean to let you know if you're actually renderer from the server-side.

<script>
import getAll from '~/plugins/api'
export default {
    asyncData (context, callback) {
        if (context.isServer) {
            getAll(function(data){
                callback(null,data);
            })
        }
    }
}
</script>

More details about Nuxt context here: https://nuxtjs.org/api/context


update: (thanks @Lanayx)

"Note: Since Nuxt.js 2.4, mode has been introduced as option of plugins to specify plugin type, possible value are: client or server. ssr: false will be adapted to mode: 'client' and deprecated in next major release."

// nuxt.config.js:

export default {
  plugins: [
    { src: '~/plugins/both-sides.js' },
    { src: '~/plugins/client-only.js', mode: 'client' },
    { src: '~/plugins/server-only.js', mode: 'server' }
  ]
}

Upvotes: 2

Related Questions