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

ReactJS客户端如何实现类似process.env的环境变量?部署于AWS S3

How to Implement Client-Side Environment Variables (Like process.env) for AWS S3-Hosted Apps

Great question! Since AWS S3 hosts static files with no server-side runtime, you can’t use process.env directly like you would on a backend—but there are two solid approaches to replicate that functionality, including the Webpack method you mentioned. Let’s walk through them step by step.

Method 1: Inject Variables at Build Time with Webpack

This is the most straightforward approach if you don’t need to switch environments without rebuilding your app.

Step 1: Set Up Your .env File

Create a .env file in your project root to store your variables. For frameworks like Create React App (which uses Webpack under the hood), variables need a REACT_APP_ prefix to avoid conflicts with system variables. For custom Webpack setups, you can use any prefix (or none, but prefixes are safer).

REACT_APP_API_BASE_URL=https://api.your-app.com
REACT_APP_APP_ENV=production

Step 2: Configure Webpack

  • If using Create React App: No need to touch the Webpack config—it automatically loads variables from .env files. Skip straight to the next step.
  • If using a custom Webpack setup: Use Webpack’s DefinePlugin to inject variables into your client code. First, install dotenv to parse the .env file:
    npm install dotenv --save-dev
    
    Then update your webpack.config.js:
    const webpack = require('webpack');
    const dotenv = require('dotenv').config({ path: './.env' });
    
    module.exports = {
      // ... your existing Webpack config
      plugins: [
        // ... other plugins
        new webpack.DefinePlugin({
          'process.env': JSON.stringify(dotenv.parsed)
        })
      ]
    };
    

Step 3: Use Variables in Client Code

Now you can reference variables just like you would on the server:

// In your React component or vanilla JS file
console.log('API URL:', process.env.REACT_APP_API_BASE_URL);

When you build your app, Webpack replaces all instances of process.env.VAR_NAME with the actual string values from your .env file—so the final static code has no reference to process.env at all, making it perfect for S3.

Method 2: Load Variables at Runtime (For Dynamic Environment Swaps)

If you want to reuse the same build bundle across multiple environments (e.g., staging vs production) without rebuilding, load variables from a static JSON file instead.

Step 1: Create a Static Config File

Add an env-config.json file to your project’s public directory (the folder that gets copied directly to S3):

{
  "apiBaseUrl": "https://api.your-app.com",
  "appEnv": "production"
}

Step 2: Load the Config on App Initialization

Fetch this file when your app starts up and attach values to the window object for easy access:

// In your app's entry file (e.g., index.js)
async function loadEnvironmentConfig() {
  try {
    const response = await fetch('/env-config.json');
    window.appEnv = await response.json();
  } catch (err) {
    console.error('Failed to load environment config:', err);
    // Fallback to default values if needed
    window.appEnv = {
      apiBaseUrl: 'https://default-api.com',
      appEnv: 'development'
    };
  }
}

// Load config before initializing your app
loadEnvironmentConfig().then(() => {
  // Initialize React/Vue/your framework here
  ReactDOM.render(<App />, document.getElementById('root'));
});

Step 3: Use Variables in Client Code

Access variables via window.appEnv:

console.log('API URL:', window.appEnv.apiBaseUrl);

When deploying to S3, you only need to swap out the env-config.json file for each environment—no need to rebuild your entire app.

Key Notes for AWS S3

  • For Build-Time Injection: After building your app, upload all static files to S3 as usual. Variables are already baked into the code.
  • For Runtime Loading: Ensure your env-config.json has the correct Content-Type (S3 usually sets this to application/json automatically, but double-check if you run into fetch errors).
  • Never Store Secrets: Client-side code is publicly accessible—never put API keys, passwords, or sensitive data in these environment variables. Keep sensitive logic on the server (e.g., AWS Lambda).

内容的提问来源于stack exchange,提问作者Emerson P. Ballen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:40:07