Bes
Bes

Reputation: 83

How to use a CloudFlare Worker Environment Variable in Quasar? (Vue)

Hello & Happy New Year!

I am facing a problem in my Quasar (v1) app in regard to environment variables. I don't want to solve this using dotenv or any other Node package as these are no longer the recommended way to use environment variables in Quasar.

So I have some local environment variables I am setting/using, following the documented best practice on the Quasar official docs:

quasar.conf.js:

    build: {
      env: {
          EXAMPLE: ctx.dev
          ? JSON.stringify('https://dev.')
          : JSON.stringify('https://prod.')
      },

This allows me to specify a different endpoint in dev and prod as I would expect, but not ideal for a few obvious reasons.

index.vue:

console.log(process.env.EXAMPLE,'<---API')

I get the expected output of my mock API endpoint. Good.

Now CloudFlare Workers' variables are globally scoped (No process.env object), so once configured in wrangler.toml, it should be possible to simply call them by name:

wrangler.toml:

[vars]
CFEXAMPLE = "example_token"

BUT this does not work (I cannot get my Quasar application to build if I include this as follows). Probably because CFEXAMPLE is not defined in my quasar.conf.js

quasar.conf.js:

    build: {
      env: {
          CFEXAMPLE: CFEXAMPLE
      },

I also cannot console.log CFEXAMPLE from my index.vue file either (but I CAN build my app and deploy to CloudFlare OK).

What is the best way to get environment variables working correctly across CloudFlare and localhost please?

Thanks

Upvotes: 2

Views: 1557

Answers (1)

Bes
Bes

Reputation: 83

Ok so thanks to Michal for the hint. In the end I did this:

Firstly create an environment.js.

environment.js:

module.exports = {
    dev:{
        NODE_ENV: 'development',
        PROXY_URL: 'xx',
        }
    },
    prod:{
        NODE_ENV: 'production',
        PROXY_URL: 'zz',
          }
    }
  }

Next import it and include a function to return the correct environmental var.

quasar.conf.js:

const config = require('./src/boot/environment.js')
module.exports = function(ctx) {
  const getEnvVar = p => {
    if (ctx.dev) return (config.dev[p])
    else return (config.prod[p])
  }
...

Finally add environment variables to env:

quasar.conf.js:

      env:{
        PROXY_URL:JSON.stringify(getEnvVar('PROXY_URL')),
        POST_TO:JSON.stringify(getEnvVar('POST_TO')),
        FIRESTORE_CREDS:JSON.stringify(getEnvVar('FIRESTORE_CREDS')),
      },

Upvotes: 0

Related Questions