Plugin only server side
Asked Answered
B

2

6

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.

Bestir answered 3/8, 2017 at 21:11 Comment(0)
S
2

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' }
  ]
}
Sample answered 5/9, 2017 at 21:37 Comment(4)
Unfortunately, with this option the plugin is still passed to the client sideLaborsaving
@Laborsaving Do you know a solution which is not passing the code to the client side?Extended
@PhilippS. Looks like mode: 'server' is the right solution as of today (nuxtjs.org/guide/plugins#client-side-only)Laborsaving
@Laborsaving Thank you! I have a middleware which should be only available on server side. Any idea how to accomplish this?Extended
S
1

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.

Selah answered 5/1 at 13:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.