Skip to main content
Coderweekend

How to set up develop, staging, and production environments in Eleventy

If you want to implement different behavior in Eleventy, e.g., remove Google Analytics when running locally, you would need separate Environment.

In this article, I will create a new production environment.

Inject environment key and value #

You can set an environment key and value by inject it before starting the eleventy server.

Mac OS (or Linux, etc)

MY_ENVIRONMENT=production npx @11ty/eleventy

Windows cmd.exe

set MY_ENVIRONMENT=production & npx @11ty/eleventy

Windows Powershell (VS Code default)

$env:MY_ENVIRONMENT="production"; npx @11ty/eleventy

I use npm on a mac, so I create scripts to run in development and production environment in a package.json file.

{
"scripts": {
"start:dev": "npx @11ty/eleventy --serve --quiet",
"start:prod": "MY_ENVIRONMENT=production npx @11ty/eleventy --serve --quiet",
"build:dev": "npx @11ty/eleventy",
"build:prod": "MY_ENVIRONMENT=production npx @11ty/eleventy"
}
}

You can choose to run in development and production environment by use the cooresponsing scripts.

# Run in development environment
npm run start:dev

# Run in production environment
npm run start:prod

Reading environment value #

They value you set will be available in your code process.env property.

You can use these in your configuration or in data files as needed.

// eleventy.config.js
const env = process.env.MY_ENVIRONMENT;

If you want to reference this in a template file, you need to expose it via data files.

For example, I create a new data file at _data/env.js.

// _data/env.js
module.exports = {
environment: process.env.MY_ENVIRONMENT,
}

Then, I can access this data from the template file.

Here is an example where I access it from nunjuck template.

{% if env.environment == "production" %}
// Add Google Analytics script in production.
{% endif %}