Using Environment Variables in Eleventy Content Pages
I had to deal with an extreme edge case in Eleventy today. Since I'm currently looking for a new job I have updated my CV recently and I decided to use the HTML version I have on this website as basis to generate a PDF that I can send to companies. When I generate the PDF I want to include my address and phone number on the CV, but I don't want to put them online and I don't want to commit them either, since the Git repository is also public.
At first I put this off and manually added my address and phone number whenever I wanted to generate a new version, but then I remembered that this is Eleventy and Eleventy is amazing and it's probably extremely easy to do this and I was right.
I want to store private data in an environment variable, since these are not stored in Git and are not automatically deployed to my server. Whenever I want to make data available to templates in Eleventy, I reach for .11tydata.js files:
// site/cv.11tydata.js
module.exports = {
cv_address: process.env.FEC_CV_ADDRESS,
cv_phone: process.env.FEC_CV_ADDRESS,
};Now, in the template governing my CV, I can use cv_address and cv_phone to render these private values. If the variable has a value, I want to render these nicely:
// site/cv.njk
{% if cv_address %}
<li><strong>Address:</strong> {{ cv_address }}</li>
{% endif %}
{% if cv_phone %}
<li><strong>Phone:</strong> {{ cv_phone }}</li>
{% endif %}
I can set the environment variable in my shell before building my site using export FEC_CV_ADDRESS="My address", but it is cumbersome to type this every time. Luckily I can reach to a great library called dotenv that allows me to define the environment variables in a file that is ignored by Git.
FEC_CV_ADDRESS="My address"
FEC_CV_PHONE="My phone number"In my Eleventy config I then import the package and call it to activate dotenv. Then everything defined in .env is available as an environment variable in Node.js.
// .eleventy.js
const dotenv = require('dotenv');
dotenv.config();