Solved - My mistake...

Gatsby only puts environment variables prefixed GATSBY_ on the client.

process.env.GATSBY_WORDPRESS_SITE_URL - set in gatsby-cloud - https://some-url.com

The Problem

Attempting to connect the client/Gatsby Frontend to WordPress to experiment with WPGRAPHQL + basic auth.

Everything seems to work on dev@ localhost:8000 && build@ localhost:9000

The URL is set as an ENV var.

process.env.WORDPRESS_SITE_URL - set in gatsby-cloud - https://some-url.com

Code shows the implementation.

<div className={testWp}>
<header>
<span>Test WordPress responding</span>
/* this doesn't work on gatsby-cloud... BECAUSE... env vars need GATSBY_ prefix
to be on accessible on frontend */
<button
onClick={() =>
fetch(`${process.env.WORDPRESS_SITE_URL}/graphql`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
query: `
{
generalSettings {
url
email
}
}
`,
}),
})
.then((res) => res.json())
.then((res) => {
setResponseToPrint(res.data);
})
}
>
Test WP
</button>
</header>
<div style={{ overflow: "auto" }}>
<pre>
<code>{JSON.stringify(responseToPrint)}</code>
</pre>
</div>
</div>

...however, the fetch requests at the live site look like this...

fetch(
"https://some-url.com/the-current-location/undefined/graphql", - not env var
{
headers: {
accept: "*/*",
"accept-language": "en-GB,en-US;q=0.9,en;q=0.8",
"cache-control": "no-cache",
"content-type": "application/json",
pragma: "no-cache",
"sec-ch-ua":
'"Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"',
"sec-ch-ua-mobile": "?0",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
},
referrer: "https://some-url.com/the-current-location",
referrerPolicy: "same-origin",
body: '{"query":"\\n {\\n generalSettings {\\n url\\n\\t\\t\\t\\t\\t\\t\\t\\temail\\n }\\n }\\n "}',
method: "POST",
mode: "cors",
credentials: "include",
}
);

The Solution

In order to fix this, simple prefix all of the environment variables that the client depends on with

GATSBY_ENV_ON_CLIENT=myclientsidevariable

Words of warning

Any env variables that end up on the client are public and can be read by the user. In this case my WP/graphql url is publically accessible and can be queried by anybody. A potential vector of attack. If this was undesirable, gatsby cloud allows users to create serverless functions. Meaning we could interact with information that the client will never have access to. More on this in the future.