Can't access gatsby environment variables on the client side

前端 未结 5 1180
旧时难觅i
旧时难觅i 2021-02-19 00:44

I set up .env file and gatsby-config.js as below.

// .env.development
GATSBY_API_URL=https://example.com/api
         


        
5条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-19 01:30

    In Gatsby, availability of your environment variables depends on many factors:

    • Execution context. Are you trying to reach the variable client-side or server-side?
    • Variable name. Names starting with GATSBY_ are treated differently.
    • Environment file name. By default, Gatsby expects these to be .env.production and .env.development.
    • DotEnv usage. Whether you're using dotenv npm package to load the env file.

    Here are the different ways to make an environment variable accessible in server and browser environments. Choose whichever fits your setup best.

    Server-side:

    1. Define an OS environment variable.

    MY_VAR='my value'; export MY_VAR // will persist in the OS environment
    npm run start
    

    OR

    MY_VAR='my value' npm run start // will set the variable for that process only
    

    Note: variable name doesn't matter.

    2. Create an env file and define variable there.

    echo MY_VAR='my value' >> .env.development
    

    Load the file in gatsby-config.js:

    require('dotenv').config({
      path: `.env.${process.env.NODE_ENV}`,
    })
    

    Note: file name doesn't matter. Variable name doesn't matter.

    Client-side:

    1. Create a .env.development (.env.production for prod environment) file and define a variable there.

    Note: file name does matter. Variable name doesn't matter.

    2. Create an environment file named differently (say .env) and define a GATSBY_ prefixed variable there.

    echo GATSBY_MY_VAR='my value' >> .env
    

    Load the file in gatsby-config.js with dotenv.

    require('dotenv').config() // .env is loaded by default, no need to specify path
    

    Note: file name does not matter. Variable name does matter.

    3. Define a GATSBY_ prefixed OS environment variable.

    GATSBY_MY_VAR='my value'; export GATSBY_MY_VAR
    npm run start
    

    OR

    GATSBY_MY_VAR='my value' npm run start
    

    Note: variable name does matter.

提交回复
热议问题