How to Use .Env Variables in Nuxt 2 or 3

How to use .env value in nuxt.config.js with runtime config

As explained in my answer here: https://stackoverflow.com/a/67705541/8816585

If you have some modules located in nuxt.config.js, you can only pass env variables through process.env.MY_VARIABLE.

It is working if you're linking to an external file tho.

How to access .env variables in a Nuxt plugin?

Set your env variable into nuxt.config.js

export default {
publicRuntimeConfig: {
segmentApiSecret: process.env.SEGMENT_API_SECRET,
}
}

And then, this one should do the trick

// segment.js
export default ({ $config: { segmentApiSecret } }) => {
!function(){var analytics=window.analytics=...analytics.SNIPPET_VERSION="4.13.2";
analytics.load(segmentApiSecret);
analytics.page();
}}();
}

UPDATE: A more in-depth answer of mine can be found here too.

Can not access process.env variables in component nuxt

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>

Unable to access .env Variables in script imported in Head of NuxtJS App

We need not to worry about these Env Variables in New Relic Provided Script. Here is the community answer to support this statement -

https://discuss.newrelic.com/t/nreum-script-exposes-license-key-in-source-code-is-it-fine/55485/2

So, ultimately I did my implementation without removing new relic variable from the script. However, in the future if somebody wanted to post how can we , The answer will be most welcome!



Related Topics



Leave a reply



Submit