Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access .env variables in a Nuxt plugin?

Segment Analytics provides a snippet with a secret API key in it. In my Nuxt.js project I created a plugin called segment.js which I registered in my nuxt.config.js:

nuxt.config.js

plugins: [
  {
    src: "~/plugins/segment.js",
    mode: 'client'
  }
]

In my plugins/segment.js file I have my snippet:

!function(){var analytics=window.analytics=...analytics.SNIPPET_VERSION="4.13.2";
analytics.load(process.env.SEGMENT_API_SECRET);
analytics.page();
}}();

Obviously I don't want to have my secret API key exposed there so I have it stored in my .env file instead:

.env

SEGMENT_API_SECRET=FR4....GSDF3S

Problem: process.env.SEGMENT_API_SECRET in plugins/segment.js is undefined so the snippet doesn't work. How can I access my .env variable SEGMENT_API_SECRET from my plugin plugins/segment.js?

like image 583
drake035 Avatar asked May 17 '21 19:05

drake035


People also ask

Can I use variables in .env file?

env file is included to use, so it's easy to have a different configuration based on the environment your app is running on. This gives you the flexibility to have different variables for local, staging, production, and even different developers' machines.


2 Answers

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.

like image 73
kissu Avatar answered Oct 28 '22 20:10

kissu


For me, I wanted to use my environment (.env) variables in my Nuxt Firebase Plugin: /plugins/firebase.js. Usually with Vue, you have to prefix these .env variables with VUE_APP_, for example: VUE_APP_yourKeyName=YOUR_SECRET_VALUE

But with Nuxt, you have to then set these .env variables in the Nuxt Config nuxt.config.js like so:

// .env
VUE_APP_yourKeyName=YOUR_SECRET_VALUE
// nuxt.config.js
export default {
    env: {
        NUXT_VAR_NAME: process.env.VUE_APP_yourKeyName,
    },
}
// /plugins/firebase.js
const firebaseConfig = {
    apiKey: process.env.NUXT_VAR_NAME,
}

You can read more about using Nuxt Environment Variables here.

NOTE: For Nuxt versions > 2.12+, in cases where environment variables are required at runtime (not build time) it is recommended to replace the env property with runtimeConfig properties : publicRuntimeConfig and privateRuntimeConfig.

like image 4
Greg Avatar answered Oct 28 '22 19:10

Greg