App Engine app.yaml handlers for built React app

Tomáš Soukup picture Tomáš Soukup · Dec 5, 2018 · Viewed 7.8k times · Source

I'm trying to deploy production build of React app (created using create-react-app) to gcloud app engine flexible enviroment.

After running npm run build, the build folder has been created:

App directory tree

This is my app.yaml:

# [START runtime]
runtime: nodejs
env: flex
# [END runtime]

# [START handlers]
handlers:
  - url: /
    static_files: build/index.html
    upload: build/index.html
  - url: /
    static_dir: build
  # [END handlers]

When deployed to App Engine, the version configuration shows:

runtime: nodejs
api_version: '1.0'
env: flexible
threadsafe: true
handlers:
  - url: /
    application_readable: false
    static_files: build/index.html
    require_matching_file: false
    upload: build/index.html
  - url: '/(.*)'
    application_readable: false
    static_files: "build/\\1"
    require_matching_file: false
    upload: 'build/.*'
automatic_scaling:
  min_num_instances: 2
  max_num_instances: 20
  cpu_utilization:
    target_utilization: 0.5

The development app is being served instead of the production version from the build folder. What am I doing wrong?

Answer

Nick Daniel picture Nick Daniel · Mar 20, 2019

Modify the scripts in package.json to have GAE use serve to serve the build dir instead of the root directory.

Upon deployment, GAE will run npm start to begin serving your application. By changing what the start script maps to, you can have the build directory served as desired. You will have to use npm run local when doing local development with this setup, as you are changing what npm start is doing.

This process requires you to run npm run build before deploying to GAE. This will serve the build directory for you, but it does not automatically run the build process for you, so that must still be done to serve your latest code in /src.

Source: https://github.com/facebook/create-react-app/issues/2077

Code:

"scripts": {
  "start": "serve -s build",
  "prestart": "npm install -g serve",
  "local": "react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test --env=jsdom",
  "eject": "react-scripts eject"
}