Crafty Aliases & Environment Variables

Note: This article was originally written in June 2019. As far as I can tell it was finished around the same time, but for some reason never published. I've tidied it up a little but otherwise assumed it's good to go.

I briefly mentioned this in my last post about Craft CMS, but I've recently spent some time getting to grips with environment variables and aliases within the Admin panel. Whilst the docs are great (see further reading below), they do leave out a little bit of the more foundational knowledge which, if you're as green to all of this as I am, can leave you scratching your head. As is the aim of this series of posts, hopefully my waffling here might save you some of that confusion.

So, what is an environment variable, what is an alias, when might you want to use them, and why are they useful? Let's break them down as best as I can. Oh, and a big thanks to Oli over on the Craft Stack Exchange who helped me understand one key missing element that had my stumped for a few hours.

Environment Variables

These are pretty much exactly what you'd expect if you've ever used a .env or env.ini file in the past: global variables that can be called anywhere within the Craft install but which keep their contents secret. The value of each variable never leaves your server environment, so the client cannot reveal them and neither can a third-party script, malicious or otherwise. Similar approaches are used in just about every backend and back-front-end language or framework, from Ruby to ReactJS, and Craft is no different.

But environment variables don't just keep key information safe, they also allow you to quickly configure different setups, all from a single file. I'm going to assume that you at least have a development environment and a production environment, so you'll know why this can be useful, but you might also have staging setups or DevOps pipelines to consider, let alone testing environments. Oh, and then there's the fact that multiple teams and various team members will likely want to run a copy of Craft locally when working on site changes or even CMS modifications. Each of these instances can have their own .env file and setup, which makes them very powerful.

Out of the box, you'll actually have a few environment variables setup without even realising it. During installation, Craft will have prompted you for some specifics like the database location and login details. Whatever you entered was stored as a set of environment variables, which you may have even tweaked to get it running on the server once you launched your website, or to change the running environment between dev and production[1].

If you have, then you'll already know (as has been hinted at above) that environment variables are stored in the .env file, which can be found in the root folder of your Craft installation. These files are incredibly simple, but very powerful. I'd advise never deleting anything from a .env file that you haven't put there yourself, but feel free to extend them as much as you want. So how do we do that?

Creating a New Variable

It really couldn't be a simpler process. Just pop open your .env file in a text editor and add a new line in the following format:

NAME_OF_VARIABLE="variable_content"

That's all there is to it! There's no need for EOL characters or arrays or anything else; just a new line, a variable name, and a value. So if I wanted to create a new base URL for my website's asset files (images, PDFs, documents, videos etc.), for example, I would simply create a new line at the bottom of the file and input the following:

ASSET_BASE_URL="https://cms.theadhocracy.co.uk/assets"

Now just save the file, refresh any open tabs containing Craft, and away you go. Oh, one last thing: you can (and probably should) add comments by starting the line with a # symbol. I tend to group elements together, so I'll have a comment for # Default website base URLs followed by all my environment variables that output URLs, like the example above.

Using Environment Variables

You can use environment variables pretty much anywhere that you can write Twig code, as well as within specific form fields in the admin control panel[2]. If (like me) you're using Craft as a headless CMS then Twig options probably aren't that useful, but they can still come in handy. To call an environment variable from within a template, just use:

{{ getenv('NAME_OF_VARIABLE') }}

Indeed, getenv() is a particularly useful PHP function that queries .env files. That means you can use the above function (without the curly braces) in any line of PHP anywhere in your Craft files, which will be important when we get to aliases.

You can even securely pass the value of an environment variable to JavaScript (or just use it in Twig) by doing the following within a Twig template (thanks to JollyR):

{% set env = getenv('NAME_OF_VARIABLE') %}
<script>
 var myVariable = '{{ env|e('js') }}'
</script>

Meanwhile, in the control panel, element variables can be used to define folder paths and URLs. A good example would be an Asset Volume folder path, as with the above; they're also often used to set the site name from within General Settings, as well as the Base URL on the site itself.

Aliases

Much like an environment variable, an alias is a way to define a globally accessible piece of information that can be utilised within templates, passed to client-side scripts securely, or used in specific areas of the control panel. Sounds completely identical, right? So why do we even need aliases? Well, the big reason is that aliases can be modified once invoked, as well as being able to be used dynamically within other strings. Let's just review what I mean by that.

Y'see, environment variables should arguably be referred to as environment constants. Once defined in the .env file, the environment variable can't be modified; you can't manipulate it or remix it, only assign its value to a different variable and then tweak that. Craft also doesn't actively parse environment variables; it performs more of a hot-swap that occurs backstage. In that sense, you can't think of them like variables in traditional programming languages. For example, you can't do the following on an Asset Volume Base URL:

$NAME_OF_VARIABLE/extra-info

Let's assume $NAME_OF_VARIABLE in the above example contains foobar. Rather than making your asset appear at https://yoursite.io/foobar/extra-info, as you intended, it will be given a path of https://yoursite.io/$NAME_OF_VARIABLE/extra-info. The environment variable becomes part of the string and never gets swapped out[3]. Why? Because if you use an environment variable within a control panel field, or in most instances across Craft, then Craft will expect it to be unchanged and alone. Trying to manipulate it in any way will simply fail.

That might all seem a bit odd, but it's done for security; if this didn't work like it does, environment variables would actually be largely pointless. Still, it makes them pretty inflexible, and can lead you to consistently add new ones as folder paths and URLs grow in complexity. As soon as that starts to happen, you should be aware that you've outgrown environment variables and should probably start using aliases instead.

Creating an Alias

Aliases provide a greater level of depth and functionality, so understandably they are a little more complex to set up. That said, it's still incredibly simple, with just one little gotcha which tripped me up a few times.

Step one is to open up your general.php file, which can be found in the config folder stored in the root of the Craft installation. You should already have a code skeleton in place, creating a PHP function that returns four arrays of settings: one for global settings which uses an asterisk (*), and one each for the three possible Craft environments i.e. dev, staging and production. Here's the gotcha: your aliases must go within one of these preexisting settings arrays, and which one you choose will determine where you can then make use of it. The most likely candidate will be the global settings array, but you might want to set specific values for dev vs. production in some instances[4].

If you haven't got any aliases set up yet, the next step will be to add a new aliases array:

'aliases' => [
 
],

[I prefer to put this near the top of Global Settings to try and maintain a vague alphabetisation in my config.]

Finally, add in your new aliases using the format:

'@aliasName' => 'Alias Value'

As this is an array, remember that all but the final value should end with a comma, but otherwise you can extend aliases as much as you want[5].

Combining Aliases & Environment Variables

Whilst you can give an alias a value directly in the general.php file, that isn't as flexible as environment variables that can be set on a per-environment basis; even if you choose to set general.php in the same manner, the file structure required is more complex, so introduces a greater risk of incorrect syntax over a .env technique. On top of which, general.php tends to be included in Git repositories, which means exposing any secure data defined directly on the alias.

As a result, the most common method of using aliases is to combine them with environment variables using the previously mentioned getenv() PHP function. This not only ensures that sensitive data remains secure whilst allowing for simpler environment customisation, it effectively extends environment variables to grant them greater functionality.

To do so, just replace the value with a getenv() function like so:

'@aliasName' => getenv('NAME_OF_VARIABLE')

Using an Alias

Aliases can be used anywhere an environment variable can be, called by using the @ symbol followed by the name as defined in the general.php file. Otherwise, alias use is very similar to environment variables, although they can be used within strings or values and will decode correctly. For example, you can easily set an Asset Volume Base URL by doing something like:

@assetBaseUrl/extra-info

For use in templates, Craft has a bespoke alias() function that works exactly as you'd expect. For example, say you have the above asset URL setup and want an <img> element within a template to use a relative path. All you'd need to do is:

<img src="{{ alias('@assetBaseUrl/images/name.png') }}">

It's that simple!

Explore Other Articles

Further Reading & Sources

Conversation

Want to take part?

Comments are powered by Webmentions; if you know what that means, do your thing 👍

Footnotes

  • <p>Craft CMS has the ability to accept environment variables as well as aliases. It can be worthwhile understanding how these two seemingly similar concepts differ, and when you might want to use one over the other.</p>
  • Murray Adcock.
Article permalink

Made By Me, But Made Possible By:

CMS:

Build: Gatsby

Deployment: GitHub

Hosting: Netlify

Connect With Me:

Twitter Twitter

Instagram Instragram

500px 500px

GitHub GitHub

Keep Up To Date:

All Posts RSS feed.

Articles RSS feed.

Journal RSS feed.

Notes RSS feed.