Peter Boomsma
Peter Boomsma

Reputation: 9806

Set development or production api URL from .env in Nuxt

For some reason my ternary statement is not working correctly. If I run my Vue Nuxt application like this

.env

USE_DEV_API='true'

nuxt.config.js

const result = process.env.USE_DEV_API ? process.env.USE_DEV_API + ' true' : process.env.USE_DEV_API + ' false'

Result is as expected:

true true

If I change USE_DEV_API in the .env to false:

USE_DEV_API='false'

Result is:

false true

The strange thing is that if I set the USE_DEV_API to false I do get the expected false false result:

const result = false ? process.env.USE_DEV_API + ' true' : process.env.USE_DEV_API + ' false'

Result:

false false

Upvotes: 1

Views: 3145

Answers (2)

Dan
Dan

Reputation: 63089

process.env

This happens because the .env variable is set to the string 'false' rather than the keyword false. And all JavaScript strings evaluate to true except for the empty string ''.

This isn't just a matter of having placed quotes in the .env file. The issue is with the way process.env works, and you can read it in the docs:

Assigning a property on process.env will implicitly convert the value to a string.

Nuxt

Since you are using Nuxt, you already have access to the environment information, and you can use this to automatically select your api:

process.env.NODE_ENV  // 'development', 'production'

Solution

Store just your api URLs in .env, for example:

DEV_API=http://mydevapi.com
PROD_API=http://myprodapi.com

(Notice quotes aren't needed since it's all strings anyway.)

Now you can test the node environment and automatically select the right api:

const dev = process.env.DEV_API;
const prod = process.env.PROD_API;
const api = process.env.NODE_ENV === 'development' ? dev : prod;

This way is better because you don't have to remember to switch your flag every time you build or run in production, because it happens automatically.

Upvotes: 4

Nicolas Pennec
Nicolas Pennec

Reputation: 7631

Your var env is a string, not a boolean. Th value from .env file will always be truthy because it's a string empty or not.

So you can update your test as follows in order to convert the string to boolean:

const result = (process.env.USE_DEV_API === 'true') ? process.env.USE_DEV_API + ' true' : process.env.USE_DEV_API + ' false'

For more details see How can I convert a string to boolean in JavaScript?

Upvotes: 0

Related Questions