Set Graphql URI in React with .env

Viewed 181

I'm trying to develop using localhost on one machine (via localhost:5000/graphql) and using Github codespaces on another (via https://githubuser-repo-wackycode-5000.githubpreview.dev/graphql).

In my index.tsx I have:

const graphqlHost: string = (process.env.GRAPHQL_HOST as string);

console.log(graphqlHost);

const httpLink = createHttpLink({
  uri: graphqlHost,
  credentials: 'same-origin'

});

My .env (located just outside of /src looks as follows:

# GRAPHQL_HOST="localhost:5000/graphql"
GRAPHQL_HOST="https://githubuser-repo-wackycode-5000.githubpreview.dev/graphql"

enter image description here

Error I'm getting (obviously not resolving .env): Module not found: Can't resolve 'graphql'

Everything does would when the uri is hardcoded.

What's the proper .env setup I'm missing?

2 Answers

Could you try something like this? The .env files doesn't need quotes.

GRAPHQL_HOST=https://githubuser-repo-wackycode-5000.githubpreview.dev/graphql

If that doesn't work try to create a dummy key and check if you can get it.

.env

DUMMY=dummy

index.tsx

const graphqlHost: string = (process.env.DUMMY as string);

As per this answer I had to use the prefixed REACT_APP_.

.env

REACT_APP_GRAPHQL_HOST=https://githubuser-repo-wackycode-5000.githubpreview.dev/graphql

index.tsx

const graphqlHost: string = (process.env.REACT_APP_GRAPHQL_HOST as string);

const httpLink = createHttpLink({
  uri: graphqlHost,
  credentials: 'same-origin'

});

Also as recommended by Github I added the .env variable to my Codespace... therefore I can spin up another instance without worrying about updating my .env on the Codespace.

Related