user6221709
user6221709

Reputation:

how to access vue.js api key in laravel application

hello there i am trying to access my youtube api key located in the .env file from within this code:

<template>
   <div class="YoutubeDash__wrapper">
      <video-group :videos="videos"></video-group>
   </div>
</template>

<script>
  import VideoGroup from './VideoGroup.vue';
  import Search from './Search';

  export default {
    components: {
      VideoGroup
    },
    created(){
      Search({
        apiKey: process.env.VUE_APP_SECRET,
        term: 'laravel repo'
      }, response => this.videos = response);
    },

    data(){
      return {
        videos: null
      }
    }
  }
</script>

According to the documentation using env variables with vue.js. Everything seems to be correct. In my .env file i say: VUE_APP_SECRET=xxxxxxxxxxxxxxx, what am i missing here ?

I get this error message:

app.js:37809 Error: YouTube search would require a key

Any tips are welcome! Thanks a lot!

Upvotes: 1

Views: 2262

Answers (2)

Aviram
Aviram

Reputation: 553

I prefer excluding laravel-mix from this process.
Usually, in my blade entry-point I use meta tags:

<meta name="myVal" content="{{ config('<any-config-key>') }}">

<any-config-key> can be any laravel configuration key including those taken from .env.
Then, in my javascript I do something like:

const setVueGlobal = (metaHeaderName, vueGlobalName) => {
    let value = document.head.querySelector('meta[name="' + metaHeaderName + '"]').content;
    if (!value) {
        console.error('some error msg');
        return null;
    }

    Vue.prototype[vueGlobalName] = value;
    return value;
};

setVueGlobal('myVal', '$myVal');

Finally, accessing using this.$myVal

Upvotes: 0

milo526
milo526

Reputation: 5083

We need to work with a small amount of information here so I am going to make a few assumptions (based on the tags) mostly that you are using laravel and laravel-mix to compile your resources.

For laravel(-mix) to make your .env variables accessible by JS you need to prefix them with MIX_ i.e. MIX_VUE_APP_SECRET. This will make your variable accessible as process.env.MIX_VUE_APP_SECRET.

Upvotes: 1

Related Questions