2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Nuxt で環境変数を使用するときに気をつけること

Posted at

はじめに

※ Nuxt v2.15.8 を使用しております。

Runtime config プロパティはキャストされる

Nuxt で環境変数を扱うには、 env プロパティRuntime config プロパティ があります。 env プロパティから Runtime config プロパティへ移行したところ環境変数がキャストされ、同値演算子( === )で比較している式が失敗するという不具合に遭遇しました。(以下のような issue も立てられています。)

再現

.env nuxt.config.js pages/index.vue の各ファイルに以下を記述します。

.env
TEXT=text
NUM=123
FLAG=true
nuxt.config.js
export default {
  ...
  env: {
    text: process.env.TEXT,
    num: process.env.NUM,
    flag: process.env.FLAG,
  },
  publicRuntimeConfig: {
    text: process.env.TEXT,
    num: process.env.NUM,
    flag: process.env.FLAG,
  },
}
pages/index.vue
...
export default Vue.extend({
  name: 'IndexPage',
  mounted() {
    console.log('--- env プロパティ ---')
    console.log(`${process.env.text}: ${typeof process.env.text}`)
    console.log(`${process.env.num}: ${typeof process.env.num}`)
    console.log(`${process.env.flag}: ${typeof process.env.flag}`)
    console.log('--- Runtime config プロパティ ---')
    console.log(`${this.$config.text}: ${typeof this.$config.text}`)
    console.log(`${this.$config.num}: ${typeof this.$config.num}`)
    console.log(`${this.$config.flag}: ${typeof this.$config.flag}`)
  },
})

コンソールログを確認します。

--- env プロパティ ---
text: string
123: string
true: string
--- Runtime config プロパティ ---
text: string
123: number
true: boolean

対策

以下のように .env ファイルで値をダブルクォートで囲んだり、 nuxt.config.js ファイルで文字列として設定してもキャストされます。

.env
TEXT=text
# ダブルクォートで囲んでもキャストされる
NUM="123"
FLAG="true"
nuxt.config.js
export default {
  ...
  publicRuntimeConfig: {
    text: process.env.TEXT,
    // テンプレートリテラルを使用しても number 型にキャストされる
    num: `${process.env.NUM}`,
    // 空文字列を足しても boolean 型にキャストされる
    flag: process.env.FLAG + '',
  },
}

対策1: 環境変数で扱う値を string 型にする

上記の再現の場合、 FLAG=true は改善できます。例えば FLAG によってノーマルモードとハードモードに分けている場合は以下のように命名を MODE などに変更し、 boolean 型以外の値を設定します。

.env
- FLAG=true
+ MODE=hard

対策2: コード上で環境変数を string 型にキャストする

環境変数を使用するときにテンプレートリテラルなどを使用して、 string 型にキャストします。

if (`${this.$config.num}` === "123") {...}

おわりに

nuxt.config.js ファイルで文字列として設定してもキャストされるのは厄介です。ですので、環境変数で扱う値を初めから string 型になるように定義することでキャストされることを未然に防ぎましょう。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?