Frontend - React 에서 env 파일에 key 저장하는 방법

2023. 11. 15. 20:39Today I Learned (TIL)

To use environment variables in your JavaScript/JSX files, you can leverage a tool like dotenv to load the environment variables from a .env file. Here's a step-by-step guide:

1. Install dotenv: Run the following command in your project's root directory to install dotenv as a dependency.

npm install dotenv


2. Create a .env file
: Create a file named .env in your project's root directory and add the following line:

REACT_APP_KAKAO_API_KEY=1234kd98dgadgad09d9f0gs8...

Note: It's a convention to prefix environment variables with REACT_APP_ when using Create React App. (This is the most important information for me😅)

3. Update your code to use the environment variable:
js file 중 api key 를 넣어야 하는 곳에 위에서 만들어준
REACT_APP_KAKAO_API_KEY를 적어준다.

#example

if (!existingScript) {
      const script = document.createElement("script");
      script.src = "https://cdn.kakaopay.com/ka-kit/secure/kakaopay.latest.js";
      script.async = true;

      script.onload = () => {
        window.Kakao.init(process.env.REACT_APP_KAKAO_API_KEY);
      };