Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not access process.env variables in component nuxt

In nuxt config I have env object

env: {
    hey: process.env.hey || 'hey'
},

as soon as I want to display it in component template:

{{ process.env.hey }}

I got an error

Cannot read property 'env' of undefined

Any idea what can cause that?

like image 394
BT101 Avatar asked Dec 19 '19 16:12

BT101


People also ask

How do you use environment variables in NUXT?

Nuxt lets you create environment variables client side, also to be shared from server side. The env property defines environment variables that should be available on the client side. They can be assigned using server side environment variables, the dotenv module ones or similar.

Can I use Vue 3 with NUXT?

Nuxt 3 is the next generation of the popular hybrid Vue framework, which allows us to use Vue for building server-side rendered applications. Beta version was launched on 12 October 2021, bringing into Nuxt Vue 3, a new intro engine, a lighter bundle and adhook Vite.

How do I view environment variables in Nextjs?

Next.js comes with built-in support for environment variables, which allows you to do the following: Use .env.local to load environment variables. Expose environment variables to the browser by prefixing with NEXT_PUBLIC_


1 Answers

Nuxt < 2.13

process isn't directly available to templates, but you can access it by creating a computed property or adding it to your component's state. Here's an example:

<template>
  <div>{{ message }}</div>
</template>
export default {
  computed: {
    message() {
      return process.env.hey;
    },
  },
};

Nuxt >= 2.13

You can now use the runtime config like so:

nuxt.config

export default {
  publicRuntimeConfig: {
    message: process.env.hey || 'hello world!',
  },
};

template.vue

<template>
  <div>{{ $config.message }}</div>
</template>
like image 69
David Weldon Avatar answered Oct 24 '22 20:10

David Weldon