I love Netlify’s branch deploy feature. It allows you to automatically deploy a code located in a git branch on a different domain than your master/main branch. Whenever I write a new article I write it in a branch and then I can preview the article on the web on the branch domain. I wanted to forbid indexing of such branch deploys by robots like Google so the content doesn’t end up in the Google index. Here is how you can do it in Jekyll. But the same procedure will work in different site generators such as Hexo.

Whenever Netlify builds your code it exposes a few environment variables in the build environment. These variables contain useful information such as git branch being built, Ruby version used, etc. Unfortunately, Jekyll won’t let you access all these variables out of the box, you need to use a plugin for it. Without any plugin, you can read the JEKYLL_ENV variable. This variable is usually used for distinguishing between a local build on your machine and a production build on Netlify. It’s hard to use it to distinguish between a branch build and a production build.

If you install the jekyll-environment-variables plugin you can suddenly access all the environment variable in your templates. The variables will be stored in the site.env variable as an associative array. You can see all the variables when adding {{ site.env | inspect }} in your template somewhere and let Netlify deploy it. But be aware that there may be some sensitive data. You’ll see something like this:

"SITE_ID"=>"de810d55-0c24-45ef-8f3e-fefa09edb71f",
"LANGUAGE"=>"en_US:en",
"BRANCH"=>"branch-build",
"COMMIT_REF"=>"8519d637c54337779480d8d5ccc316b51e27a505",
"CONTEXT"=>"branch-deploy",

We’re interested in two variables: BRANCH and CONTEXT. The BRANCH variable holds a git branch being built while the CONTEXT tells you directly if it is a build from a non-production branch or if it is a production build. For a production build, you get CONTEXT=production, for a branch build you get CONTEXT=branch-deploy. To forbid Google and other nice robots to index my branch deploy I added this line to my template:

{% if site.env.CONTEXT == "branch-deploy" %}
	<meta name="robots" content="noindex, nofollow">
{% endif %}

The same thing can be done by comparing the BRANCH to anything else than master or whatever is your main production branch:

{% if site.env.BRANCH != "master" %}
	<meta name="robots" content="noindex, nofollow">
{% endif %}

If you need, you can even inject some code for a specific branch:

{% if site.env.BRANCH == "my-special-branch" %}
	<script>console.log("something-special");</script>
{% endif %}