Search code examples
environment-variablesgatsbydotenv

How to specify an URL in .env file of Gatsby app?


Just in case, I'd like to know against Gatsby app, in case its settings differ from other node based apps.

I want to refactor gatsby-config.js by moving http://localhost:1337 to .env.

From

plugins: [
  {
    resolve: `gatsby-source-strapi`,
    options: {
      apiURL: `http://localhost:1337`,
    },
  },
]

To

plugins: [
  {
    resolve: `gatsby-source-strapi`,
    options: {
      apiURL: process.env.STRAPI,
    },
  },
]

and .env as follows didn't work for me:

STRAPI=$(http://localhost:1337)


Solution

  • Create a file in the root of your project named .env.development and .env.production. There, create your variable, just:

    STRAPI= "http://localhost:1337"
    

    In your gatsby-config.js add the following snippet (above module exportation):

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

    Finally, leave the configuration just with:

    plugins: [
      {
        resolve: `gatsby-source-strapi`,
        options: {
          apiURL: process.env.STRAPI,
        },
      },
    ]
    

    By default, Gatsby will take the .env.development or .env.production when running gatsby develop or gatsby build respectively, allowing you to pass the environment variables to the server files (gatsby-config.js, etc).