Access Netlify env variables in Jekyll config file to hide API keys

Hi there,

https://reverent-volhard-34212c.netlify.app/ is built on Jekyll.

I have set a Netlify environment variable with an Airtable API key.

I’ve installed the jekyll-dotenv gem so I can access the Netlify environment variable. This works when I use Liquid in layouts and includes (i.e. with {{ site.env.NETLIFY_ENV_VARIABLE_NAME }}).

However, I want to be able to access the variable in my site’s _config.yml file. I can’t do this as this is where I set my site variables, and Liquid won’t work here.

So my questions are:

  • Is there a way to access Netlify environment variables in Jekyll’s _config.yml file?
  • Is there a different approach to hiding API keys in Jekyll when the site is deployed from Github? (I don’t want to use a private repo.)

TIA,

Leon

1 Like

Hi @leonp,

The only option for you would be to use Jekyll to build that _config.yml file for you. But this is going to be a circular reference, as Jekyll will probably need that file to build the site and that file would need to be dynamically built by Jekyll.

In that case, you’d have to resort to some other build tool (like a Node.js script), to generate the file during the build time before running Jekyll build.

Thanks for your answer, @hrishikesh, I thought that might be the case.

I’ll consider that, or maybe even using an SSG that allows for secret keys a little more easily (eleventy, for example).

1 Like

i am having the exactly same question. did you find a solution on this?

The solution is mentioned above.

sorry I’m a beginner here. can you elaborate?

You can use something like yaml-to-json - npm (npmjs.com) to convert your config file to JSON, then in that JSON, add the environment variables from Netlify, and then use something like: json-to-pretty-yaml - npm (npmjs.com) to convert the updated JSON back to YML that you can write to disk using Writing files with Node.js | Node.js (nodejs.org).

but how can i do these steps on netlify?
i have to run these steps in serial on netlify, correct?

Yes, you need to write code for that. Netlify won’t be helping you write the code.