Eleventy tip: how to use environment variables

Each project, even the statically-generated one, will eventually require information that should not be exposed in the repository. For example, Google Analytics ID or a website URL address (required by most static-site-generators for creating absolute URL's) will differ, depending on the deployed host.

There's a de facto standard way of handling such cases in development projects - dotenv package and its .env file. Let's see how we can integrate Eleventy with dotenv in few simple steps.

  1. Install dotenv package

    npm install --save-dev dotenv

    or if you use yarn

    yarn add dotenv
  2. On the top of your .eleventy.js file put the below line:

    require('dotenv').config();

    // rest of your 11ty configuration here
  3. Create a file called .env and put variables that will be used during site generation.

    SITE_URL=http://localhost:8080/
    

    Remember to include the above file in your .gitignore to keep those data out of your code!

  4. Create a data file (e.g. _data/metadata.js) which will collect your variables for SSG usage

    module.exports = {
    "SITE_URL": process.env.SITE_URL || '/'
    }

Now you can use your variable anywhere in your code! Try it by entering in your base layout file:

<pre>
My site URL is:
{{ metadata.SITE_URL }}!
</pre>

There's also last step - not required, but strongly recommended - to create a file containing all possible ENV variables, so that any other developer will know which variables are already in use.

Let's create a file called .env.example and put all environment variables used in your project there. This file should be included to the repository.
For the above example it would be like:

SITE_URL=http://example.com/

Remember to not put there any real and confidential values! These are meant to be examples for a developer!

As you can see, in few simple steps we got rid of hard-coding values that should be kept safe.