Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
930 views
in Technique[技术] by (71.8m points)

environment variables - Cannot read env file on Gatsby when using Docker

I have a problem with Docker, essentially I have created an .env file which is used by the frontend service like this:

  frontend:
    container_name: begreentannery_frontend
    build: 
      context: ./frontend/
      args: 
        API_URL: ${API_URL}
        MAILCHIMP_ENDPOINT: ${MAILCHIMP_ENDPOINT}
        FORM_KEY: ${FORM_KEY}
        GOOGLE_ANALYTICS_ID: ${GOOGLE_ANALYTICS_ID}
        GOOGLE_TAG_MANAGER_ID: ${GOOGLE_TAG_MANAGER_ID}
        FACEBOOK_PIXEL_ID: ${FACEBOOK_PIXEL_ID}
    ports:
      - '3001:80'
    depends_on:
      - backend

the backend service is actually a website maded with Gatsby. When I start the app doing docker-compose up —build I can see that the variables are correctly passed in gatsby-config, eg:

console.log("API_URL:",process.env.API_URL)

but if I try to read the same variable in a component I get undefined.

How is that possible? Why I can read all the env variables inside gatsby-config.js but not in a component?

question from:https://stackoverflow.com/questions/65923950/cannot-read-env-file-on-gatsby-when-using-docker

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How is that possible? Why I can read all the env variables inside gatsby-config.js but not in a component?

Because there are server-side environment variables and client-side environment variables. The first ones (server-side) are only available in the Node server (gatsby-config.js, gatsby-node.js, etc) while the seconds (client-side) only in the browser (the rest of the components, pages and templates).

To make an environment variable available to the browser, you need to prefix it with GATSBY_ prefix, as the docs points:

In addition to these Project Environment Variables defined in .env.* files, you could also define OS Env Vars. OS Env Vars which are prefixed with GATSBY_ will become available in browser JavaScript.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...