Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to utilize a global server-side variable in Nuxtjs version 2 is to use the plugin feature. Here are the steps:

  1. Create a new file in the "plugins" directory, for example "my-plugin.js".
  2. In the file, define the variable and export it:

    export const myGlobalVariable = "Hello world!";
    
  3. In the "nuxt.config.js" file, add the plugin:

    plugins: [
     { src: "~/plugins/my-plugin.js", ssr: true }
    ],
    
  4. Now you can use the variable in any component or page:

    import { myGlobalVariable } from "~/plugins/my-plugin";
    
    export default {
     created() {
       console.log(myGlobalVariable); // output: "Hello world!"
     }
    }
    

Note that the "ssr" option in the plugin configuration is important to make the variable accessible during server-side rendering.