React项目添加.env文件隐藏API Key遇问题求助
Hey there! Let's break down the issues that might be stopping your API key from working correctly in Create React App. I've helped folks work through this exact problem plenty of times, so let's go step by step:
1. Fix Your .env File Name First
You mentioned creating a file named process.env—that's the first mistake! The file needs to be exactly named .env (just a dot followed by "env", no extra text) and placed in your project's root directory (right next to your package.json file). Create React App automatically looks for this specific filename to load environment variables.
2. Double-Check Your .env File Content
Your variable name is correct (it starts with REACT_APP_, which is required for Create React App to pick it up), but let's clean up the syntax:
- Remove the single quotes around your key. The line should look like this:
REACT_APP_API_KEY=my-secret-api-key - Make sure there are no spaces around the equals sign (
=). Spaces can cause unexpected parsing issues.
3. Correctly Reference the Key in App.js
When you use the key in your fetch request, you need to call it directly as process.env.REACT_APP_API_KEY—no extra wrapping or tricks. Here's an example of how that should look:
fetch(`https://your-api-endpoint.com/data?api_key=${process.env.REACT_APP_API_KEY}`) .then(response => response.json()) .then(data => console.log(data)) .catch(err => console.error(err));
Avoid assigning it to another variable unless necessary, and don't try to stringify it or add quotes around it in the code—Create React App handles the injection automatically.
4. Restart Your Development Server (Properly!)
You said you restarted Yarn, but make sure you shut down the running server completely before restarting. Sometimes partial restarts don't pick up changes to .env files. Close the terminal tab where yarn start is running, then run yarn start again from scratch.
5. Don't Forget to Ignore .env in Git
This is a critical step to keep your key safe! Make sure your .gitignore file includes a line for .env—otherwise, you might accidentally commit your secret key to GitHub. If .gitignore doesn't have it, add this line:
.env
Quick Test to Verify
To make sure the variable is loading correctly, you can add a console.log(process.env.REACT_APP_API_KEY) at the top of your App.js file. When you run the app, check your browser's dev tools console—you should see your key printed there (but remember to remove this log before deploying!).
内容的提问来源于stack exchange,提问作者Biii

