在Google App Engine Node.js环境中访问process.env异常问题
Hey there, let's unpack why those GAE-specific environment variables like GAE_APPLICATION or GAE_DEPLOYMENT_ID aren't showing up in your React app—this is a super common gotcha when deploying frontend apps on App Engine!
The root cause: Frontend vs. Backend Context
First, remember that React is a frontend library. When you deploy a standard React app (especially one built with Create React App), it gets compiled into static HTML/CSS/JS files that run directly in the user's browser—not on App Engine's Node.js runtime.
The process.env object you're logging is a Node.js-specific feature, meant for server-side code. Once your React app is built and served statically, the browser-side JavaScript has no access to the server's process.env variables. The only values you'll see (like NODE_ENV: "production" and PUBLIC_URL: "") are the ones Create React App automatically injects at build time as part of its tooling.
How to get GAE variables into your React app
If you need those GAE environment variables in your frontend code, here are two reliable approaches:
Use Create React App's custom environment variable system: CRA requires any custom env vars meant for the frontend to start with
REACT_APP_. To pass GAE's variables into your build, define them in yourapp.yamland reference them in your build script:# app.yaml env_variables: REACT_APP_GAE_APPLICATION: $GAE_APPLICATION REACT_APP_GAE_ENV: $GAE_ENVThen update your
package.jsonbuild script to pass these variables during the build process:"scripts": { "build": "REACT_APP_GAE_APPLICATION=$REACT_APP_GAE_APPLICATION REACT_APP_GAE_ENV=$REACT_APP_GAE_ENV react-scripts build" }You can now access these in your React code like
process.env.REACT_APP_GAE_APPLICATION.Serve React via a Node.js server: If you need runtime access to GAE variables (instead of baking them into the build), set up a simple Express server that serves your static React files. You can inject the env vars into your
index.htmltemplate (using something like EJS) before sending it to the client. This way, the variables are available in the browser's global scope or directly in your React code.
Double-check your App Engine config
Make sure your app.yaml is configured to use the Node.js runtime properly. If you're using a static_files handler to serve your React build directly without a Node.js server running, those GAE environment variables won't be available at all—there's no Node.js process to expose them. Instead, set up a server script (like server.js with Express) and configure app.yaml to use it:
runtime: nodejs20 service: your-service-name handlers: - url: /static static_dir: build/static - url: /(.*) secure: always redirect_http_response_code: 301 script: auto
内容的提问来源于stack exchange,提问作者Francesco Clementi

