LoginSignup
0
0

APIキーを.envファイルに格納する

Posted at

はじめに

APIキーをどこに書けばいいか悩んだときに調べた結果のメモ

問題

下のようにAPIキー(テキトー)を直接ソースコードに書くのは多分だめだろうけど、じゃあどうすればいいの?

useEffect(() => {
        const access_weather = async () => {
            const response = await fetch(
                'https://api.openweathermap.org/APIKEY=129ahdfa8p3917ga8891d'
            )
            const body = await response.json()
            console.log(body)
        }
        return () => {
            access_weather()
        }
    }, [])

解決方法

ルートディレクトリ直下に.envファイルを作成する
「.gitignore」などと同じ階層

ViteでReactプロジェクトを作成した場合

頭にVITE_をつけないとだめらしい

VITE_WEATHER_API_KEY=129ahdfa8p3917ga8891d

以下のコードでアクセスできる

console.log(import.meta.env.VITE_WEATHER_API_KEY)

create-react-appでReactプロジェクトを作成した場合

頭にREACT_APP_をつけないとだめらしい

REACT_APP_WEATHER_API_KEY=129ahdfa8p3917ga8891d

以下のコードでアクセスできる

console.log(process.env.REACT_APP_WEATHER_API_KEY)

注意

もし、このコードをGitHubにあげる場合は.envファイルを.gitignoreに記述する

*.env

おわりに

開発環境の時のみアクセスできる.env.development
本番環境の時のみアクセスできる.env.production
というのもあるらしい。使い分けはよくわからん。

.envはおそらく.environmentの略で、環境変数という意味なのだろう。

参考

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