1

I recently set up a Gatsby Cloud account for my Gatsby app. I currently have a github workflow that deploys the prod build to AWS, I want to move away from AWS and use G.C.

I have a prod backend and a staging backend, both Wordpress.

My goal is:

  • Whenever I put up a PR, I can see that preview-build targeting/pointing to my staging backend
  • When I merge a PR into master I want the prod build to point to my prod backend

Once I can accomplish the above, I can then update my dns and point to the GC server. Allowing me to leave AWS, but giving me a prod instance and an ephemeral staging instance.

Problem I am facing:

  • Whether it is a preview build from a PR or a "prod" build (merge to master), G.C. seems to only use my development env values.
  • I dont see a way to kick off a specific build script based on a G.C. env var, I am currently using GATSBY_IS_PREVIEW but it seems to be true in both build scenarios

Here is my gatsby-config:

let activeEnv = process.env.GATSBY_IS_PREVIEW ? "development" : process.env.NODE_ENV || "development";

require("dotenv").config({
  path: `.env.${activeEnv}`,
});
console.log(`** Build Env: '${activeEnv}'`);
console.log("** BACKEND URL:", process.env.GATSBY_GRAPHQL_URL);
console.log("** GATSBY_STRIPE_KEY:", process.env.GATSBY_STRIPE_KEY.substring(0, 10));
console.log("** GATSBY_STRIPE_SECRET_KEY:", process.env.GATSBY_STRIPE_SECRET_KEY.substring(0, 10));

Any help is greatly appreciated.

UPDATE: I followed what i saw here https://github.com/gatsbyjs/gatsby/blob/master/docs/docs/how-to/local-development/environment-variables.md

That did not work either. I updated my gatsby config to this:

if (process.env.IS_PRODUCTION_BRANCH) {
  require("dotenv").config({
    path: '.env.production'
  })
  console.log('ENV: .env.production loaded');
} else {
  require("dotenv").config({
    path: '.env.development'
  })
  console.log('ENV: .env.development loaded');
}

This ALWAYS loads the production envs, even during the PR builds which show process.env.IS_PRODUCTION_BRANCH evaluating to false. It almost seems like something is wrong with how Gatsby Cloud loads env files. Here is a screenshot of the env vars during the PR build process, somehow the .env.production is loaded.

wrong env vars

1 Answers1

1

You can use the BRANCH env var, like this:

let activeEnv = process.env.BRANCH === 'master' ? "production" : "development";
require("dotenv").config({
  path: `.env.${activeEnv}`,
});

Gatsby Cloud Env Vars