Can't access gatsby environment variables on the client side

前端 未结 5 1193
旧时难觅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条回答
  •  旧时难觅i
    2021-02-19 01:14

    A few steps & notes that should solve your problem:

    console.log(process.env) will always print empty object

    To see if it's really working, you should print the variables directly, e.g. console.log(process.env.API_URL).

    Make sure .env.* is in your root folder

    In other words, your folder hierarchy should look something like:

    .env.development
    .env.production
    src/
      pages/
        index.js
    

    You don't need to prefix with GATSBY_ if you want to access env variables server-side

    From the docs:

    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.

    You need the GATSBY_* prefix if you are using them browser-side

    The prefixing is only if you use the OS Env Vars approach (i.e. you set them directly on your server and not in these .env files).

    Kill and restart gatsby develop when you've added the .env file(s)

    I ran into this when reproducing on CodeSandbox (in CodeSandbox, you do the restart by going to Server Control Panel on the left, and clicking Restart Sandbox).

    Here's the working example: https://codesandbox.io/s/jj8xzn2y15

提交回复
热议问题