React
とRuby on Rails
を用いたポートフォリオを作成中に詰まった内容です。
問題
create-react-app
で作成したプロジェクトで.env
ファイルから環境変数を読み込めなかった。
現状
import { useAuth0 } from "@auth0/auth0-react";
export const Home = () => {
const { isAuthenticated,loginWithRedirect,logout } = useAuth0();
return (
<button onClick={() => loginWithRedirect()}>ログイン</button>
)
}
auth0にリダイレクトするために、ログインボタンを実装。そしてログインボタンを押すと以下のようになる。
https://undefined/authorize?https://undefined/authorize?client_idなんちゃらかんちゃら.......
結論
.env
を設定したあと、一度コンパイルをし直した。
Ctrl + C
から npm start
を実行すれば環境変数を読み込みできた。
やったこと
同じように悩んでいる記事がないか確認
auth0 DNS_PROBE_FINISHED_NXDOMAIN で検索
↓ヒットした記事
https://community.auth0.com/t/auth0-login-undefined-authorize-redirect/49874
Maybe my .env variables of domain and client Id aren’t being read in my index.jsx file?
Any idea if it would be an issue with my front end not pulling from .env file? Given that the redirect is not working
とあったので、いったん
const domain = process.env.REACT_APP_AUTH0_DOMAIN
const clientId = process.env.REACT_APP_AUTH0_CLIENT_ID
console.log(domain, clientId) // undefined, undefined
と出力された。
.envを確認
.env
から環境変数が読み込めていないことがわかったので、.env
を確認。
create-react-appで作成したプロジェクトの場合、.envを読み込むためには
.env変数がREACT_APP
から始まっている必要があるとのこと。
REACT_APP_
これは大丈夫そう。
.envがプロジェクト直下に配置されているか
create-react-appで作成したプロジェクト直下においてあるか確認。これも大丈夫だった。
.envを設定後にコンパイル
これで解決した。
.envを設定したら、一度Ctrl + C
で終了させ、もう一度npm start
を実行する。