DEV Community

Cover image for On the eleventh day of Enhancing: Environment Variables
Simon MacDonald for Begin

Posted on • Originally published at blog.begin.com

On the eleventh day of Enhancing: Environment Variables

Environment variables are key-value pairs that enable you to change the behavior of our application depending on the environment. Begin supports environment variables while doing local development and any of the deployed environments.

Local environment variables

Let’s test our environment variables locally before we deploy the code that uses them to a staging or production environment. The quickest way to include an environment variable locally is to create a .env file at the root of your project. Let’s add a DEBUGGING environment variable to this file.

DEBUGGING=on
Enter fullscreen mode Exit fullscreen mode

Now let’s use it in some code. Open app/elements/my-footer.mjs and update the code, so it looks like this:

export default function Element ({ html, state }) {
 const showDebugInfo = process.env.DEBUGGING === 'on'
 return html`
<footer>
 ${ showDebugInfo ? `<pre>${JSON.stringify(state, null, 2)}</pre>` : ''}
</footer>`
}
Enter fullscreen mode Exit fullscreen mode

We are reading the value of DEBUGGING from process.env. If the value is on we’ll show the debugging information. Otherwise, we’ll skip it. Open up http://localhost:3333/about and you should see:

debugging on

Now, updated the .env file so DEBUGGING is off.

DEBUGGING=off
Enter fullscreen mode Exit fullscreen mode

The http://localhost:3333/about will automatically refresh and the debugging info is gone!

debugging off

Remote environment variables

You can set up different environment variables for each of your deployed environments (see yesterday for instructions on creating environments). For our example, we are going to assume you have staging and production environments.

Let’s set our DEBUGGING environment variable to on for staging but off for production. In order to do that, execute the following commands:

begin env create --env staging --name DEBUGGING --value on
begin deploy --env staging
begin env create --env production --name DEBUGGING --value off
begin deploy --env production
Enter fullscreen mode Exit fullscreen mode

Now if you go to your staging URL you will see the debugging information:

debugging on

But, if you got to your production URL you will not see the debugging information.

debugging off

Next Steps

Speaking of debugging, how do we get the logs once we deploy to the cloud? Tune in tomorrow to find out.

Top comments (0)