PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, August 20, 2022

[FIXED] How to access .env variables in a Nuxt plugin?

 August 20, 2022     analytics, environment-variables, nuxt.js, segment     No comments   

Issue

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?


Solution

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.



Answered By - kissu
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing