Google App Engine: Modify Cloud Run Environment

2019-07-27 21:59发布

问题:

I'm trying to deploy a Next.js app which uses a custom Node.js server.

I want to inject custom build variables into the app:

next.config.js

const NODE_ENV = process.env.NODE_ENV;
const envType = NODE_ENV === `production` ? `production` : `staging`;

const envPath = `./config/${envType}`;
const { env } = require(envPath);

module.exports = {
  env: { ...env },
};

The above file is run at build time (yarn build).

The issue is that Google App Engine uses Cloud Build behind the scenes. There, the NODE_ENV is always set to development. How can I override the NODE_ENV there; i.e. how can I customize the Cloud Build used for the Google App Engine gcloud app deploy?

I can't just use Docker because of this issue.

package.json

{
  "name": "blah",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "dev": "NODE_ENV=staging node server.js",
    "build": "rm -rf node_modules/ && yarn && rm -rf .next/ && next build",
    "start": "node server.js",
    "lint": "eslint . --ext .js",
    "gcp-build": "yarn build"
  },
  "dependencies": {
    "body-parser": "^1.18.3",
    "dotenv": "^7.0.0",
    "dotenv-webpack": "^1.7.0",
    "express": "^4.16.4",
    "express-session": "^1.16.1",
    "firebase": "^5.10.0",
    "firebase-admin": "^7.3.0",
    "isomorphic-unfetch": "^3.0.0",
    "lodash": "^4.17.11",
    "next": "^8.1.0",
    "now": "^15.0.6",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "session-file-store": "^1.2.0",
    "styled-components": "^4.2.0",
    "yenv": "^2.1.0"
  },
  "devDependencies": {
    "babel-eslint": "^10.0.1",
    "eslint": "^5.16.0",
    "eslint-config-airbnb": "^17.1.0",
    "eslint-plugin-import": "^2.17.2",
    "eslint-plugin-jsx-a11y": "^6.2.1",
    "eslint-plugin-react": "^7.12.4"
  },
  "engines": {
    "node": "10.x.x"
  }
}

app.yaml

runtime: nodejs10

image

Below is the output of passing a DOGE_ENV variable from app.yaml. As you can see, it is undefined. However, NODE_ENV is development.

That is, adding the following to app.yaml does not work.

env_variables:
  DOGE_ENV: production

回答1:

Don't use NODE_ENV, create your own environment variable and use that:

App.yaml

env_variables:
  ST_ENV: Production

next.config.js

const environment = process.env.ST_ENV;
const envType = environment === `production` ? `production` : `staging`;

const envPath = `./config/${envType}`;
const { env } = require(envPath);

module.exports = {
  env: { ...env },
};