Evan
Evan

Reputation: 2507

Quasar - get API key from .env into boot files

Get the value of GOOGLE_MAP_API variable in .env file into gmap-vue.js inside boot/ directory

it's working if I use the key right away like this

  load: {
    key: 'AIzaSyCw9Txxxxxxxxxxxxx',
    ...
  }

but I would like to use the key coming from .env file like this process.env.GOOGLE_MAP_API

quasar.conf.js

module.exports = function (/* ctx */) {
  return {
    ...
    boot: [
      'gmap-vue'
    ],

boot/gmap-vue.js

import Vue from "vue";
import * as GmapVue from "gmap-vue";

Vue.use(GmapVue, {
  load: {
    key: process.env.GOOGLE_MAP_API,
    ...
  }
}

.env

GOOGLE_MAP_API='AIzaSyCw9Txxxxxxxxxxxxx'

it will return an error:

Google Maps JavaScript API warning: InvalidKey 
https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key

to summarize if I get the key from process.env it gives error

Upvotes: 0

Views: 2116

Answers (2)

zkhan
zkhan

Reputation: 81

For anyone stumbling onto this more recently, there are apparently a couple ways to get environment variables into your app/boot files:

Method 1

Per the latest Quasar docs on environment variables, you can leverage the dotenv library to parse and inject your .env variables into the env object mounted in quasar.config.js:

build: {
  env: require('dotenv').config().parsed
}

Now, everything in your .env file will be available in the process.env object everywhere in your app files (boot, components, modules, etc)

Method 2

If you use Vite - I found this explanation on Jason Watmore's Blog. Basically anything you prefix with VITE_ in your .env files is available on the import.meta.env object.

Upvotes: 0

Evan
Evan

Reputation: 2507

I've notice that when I access a String value from process.env it always adds double quotes (").

even if there's No double quotes of the string value from .env

so what I did is I use regex;

  load: {
    key: process.env.GOOGLE_MAP_API.replace(/"/g, ""),

EDIT: if you guys have better answer please give, thanks

Upvotes: 2

Related Questions