Using Environment Variables with Jekyll, Vue.js, and Netlify

Written by John Vicari

We operate in a typical QA -> Production workflow on both our front-end and back-end teams. So, what happnes when your front-end is in QA but is pointing to a Production API? Nothing good happens, son… nothing good.

As I’ve [mentioned before]({% post_url 2018-06-08-ie-still-breaking-promises-literally %}), we run a few websites built with Jekyll and Vue.js, and recently launched a new site with a similar setup. Since this site had never been released, we hardcoded a handful of QA endpoints into a Vue component. This didn’t present any issues during initial development, but when it was released (and the endpoints were updated to Production) and minor bugs were being worked on, front-end QA was pointing to back-end Production. Not good, especially if data is being manipulated.

The Solution

Create a .json file to hold your environment specific variables and make them available to your Vue component.

Define environment variables in Netlify

We’re using Netlify to deploy and host this site and have setup a QA and Production build. The build settings allow you to define environment variables, this is where you add the Jekyll environment variable.


Which would look like this in the Netlify Build & Deploy settings (your development build would obviously be set to development, although I think development might be the default): Netlify Environment Variable Setting{: .img-fluid }

Create JSON file

In the root of your project create a .json file, something like environment-variables.json. Within that file we have:

{% raw %}
{% if jekyll.environment == "production" %}
    "productionUrlA": "",
    "productionUrlB": "",
    "productionUrlC": ""
{% else %}
    "qaUrlA": "",
    "qaUrlB": "",
    "qaUrlC": ""
{% endif %}
{% endraw %}

Be sure to open the file with empty front matter so Jekyll knows to process it. When Jekyll builds, environment-variables.json will be in your _site directory with only one set of environment variables ready for your Vue component to use.

    "qaUrlA": "",
    "qaUrlB": "",
    "qaUrlC": ""

Note: Jekyll will interpret line breaks where your conditional statements are, if that annoys you, start the JSON syntax at the end of the conditional line.

Fetch the environment variables in your Vue component

Set the empty data:

data: function() {
  return {
    environmentVariables: {}

Fetch your JSON:

created: function() {
  .then(response => response.json())
  .then(response => {
    this.environmentVariables = response;
  .catch(error => {

Now your variables are set in the environmentVariables object and ready to be used in your component.

Data crisis averted!

Published October 17, 2018 by

undefined avatar
John Vicari Sr. Front End Developer (Former)

Suggested Reading