0
0

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.

Nuxt3で.envに環境変数置きたい備忘録

Posted at

Nuxt3でAPIを使いたい

コードにAPIキーベタ書きはアカンので.envファイルに書いてコンポーネントから読み込む

1 .envファイルを用意する

プロジェクトルートディレクトリに.envファイルを用意

.env
API_KEY_HOGE = HOGEHOGE
API_KEY_FUGA = FUGAFUGA

2 nuxt.config.tsに記述する

nuxtの設定ファイルでruntimeConfigプロパティを定義する

nuxt.config.ts
  runtimeConfig: {
    apiKeyHoge: process.env.API_KEY_HOGE,
    public: {
      apiKeyFuga: process.env.API_KEY_FUGA,
    },
  },

runtimeConfig直下に記載すると、サーバーサイドのみで読み込み可能。
public下に記載すると、クライアントサイドからも読み込める。

3 コンポーネントから読み込む

App.vue
<script lang="ts">
const runtimeConfig = useRuntimeConfig();
const apiKeyHoge = runtimeConfig.apiKeyHoge;
const apiKeyFuga = runtimeConfig.public.apiKeyFuga;
<script>

4 参考記事

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?