You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React应用本地环境变量正常但Netlify配置后失效问题求助

Hey there! Let's work through this environment variable issue you're hitting with your React app on Netlify. I get that it works locally but breaks once deployed—super frustrating, right? Let's break down the fixes and checks you can try:

1. Stick to CRA's Environment Variable Naming Rule

Create React App (CRA) requires all environment variables (even for production) to start with REACT_APP_. Your current code uses process.env.SPEECH_ID for production, but CRA won't inject this variable because it lacks the required prefix.

Here's the simple fix:

  • Rename your Netlify environment variable to REACT_APP_SPEECH_ID
  • Simplify your code to remove the environment check entirely (CRA handles this for you):
const appId = process.env.REACT_APP_SPEECH_ID;
export default appId;

This works for both local development and Netlify production builds—CRA will automatically pick up the variable based on your environment.

2. Double-Check Netlify's Variable Configuration & Deployment Trigger

Make sure you added the variable in the right place:

  • Go to your Netlify site's Site Settings > Build & Deploy > Environment > Environment Variables
  • After adding/updating the variable, you need to trigger a fresh deployment (either push a new commit, or go to the Deploys tab and click "Trigger deploy > Deploy site"). Netlify doesn't apply new environment variables to existing deployments automatically.

3. Verify Variables in Netlify's Deployment Logs

When Netlify builds your app, it logs all loaded environment variables. Head to the Deploys tab, open your latest deployment log, and search for "Environment variables". Look for your REACT_APP_SPEECH_ID—if it's not listed, that means your variable wasn't loaded correctly (check for typos in the variable name, or make sure it's added at the site level, not team level).

4. Test Production Build Locally

To rule out code issues, simulate a production build on your machine:

  1. Run npm run build to create a production-ready build
  2. Install serve if you haven't: npm install -g serve
  3. Serve the build folder: serve -s build
  4. Visit the local production site (usually http://localhost:3000) and check if the variable works. If it fails here, the issue is with your code or local environment variable setup, not Netlify.

5. Avoid Unnecessary Environment Checks

Your original code checks NODE_ENV to switch variables, but this is redundant with CRA's behavior. CRA injects all REACT_APP_ variables regardless of environment, so you don't need to handle this manually. Keeping the code simple reduces the chance of bugs.

Hopefully one of these steps fixes your issue—let me know if you need to dig deeper!

内容的提问来源于stack exchange,提问作者aravind ks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 15:43:15